Indexers
Access objects with array-like syntax.
Indexers is a free C# Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C# Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
What Is an Indexer?
An indexer lets an object be accessed with [ ] syntax, like an array. You define it with this[...]. It is perfect for collection-like classes.
using System;
class Week
{
private string[] _days = { "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" };
public string this[int index] => _days[index];
}
class Program
{
static void Main()
{
var w = new Week();
Console.WriteLine(w[0]);
Console.WriteLine(w[6]);
}
}Indexer Syntax
An indexer looks like a property but uses this and takes a parameter list in brackets. It has get and optionally set.
using System;
class Scores
{
private int[] _data = new int[5];
public int this[int i]
{
get { return _data[i]; }
set { _data[i] = value; }
}
}
class Program
{
static void Main()
{
var s = new Scores();
s[0] = 90;
s[1] = 75;
Console.WriteLine(s[0] + ", " + s[1]);
}
}Read and Write Through the Indexer
With both a getter and setter, you can assign and read elements just like an array, while the class controls the underlying storage.
using System;
class Grid
{
private int[] _cells = new int[3];
public int this[int i]
{
get => _cells[i];
set => _cells[i] = value;
}
}
class Program
{
static void Main()
{
var g = new Grid();
for (int i = 0; i < 3; i++) g[i] = i * 10;
Console.WriteLine(g[0] + ", " + g[1] + ", " + g[2]);
}
}Validation in an Indexer
Because an indexer is just code, you can validate the index and throw a clear error for out-of-range access.
using System;
class SafeList
{
private int[] _data = new int[3];
public int this[int i]
{
get
{
if (i < 0 || i >= _data.Length)
throw new IndexOutOfRangeException("Bad index: " + i);
return _data[i];
}
set { _data[i] = value; }
}
}
class Program
{
static void Main()
{
var list = new SafeList();
list[1] = 42;
Console.WriteLine(list[1]);
}
}String-Keyed Indexers
Indexer parameters are not limited to int. A string key turns your class into a dictionary-like lookup.
using System;
using System.Collections.Generic;
class Config
{
private Dictionary<string, string> _map = new Dictionary<string, string>();
public string this[string key]
{
get => _map.ContainsKey(key) ? _map[key] : "(none)";
set => _map[key] = value;
}
}
class Program
{
static void Main()
{
var c = new Config();
c["theme"] = "dark";
Console.WriteLine(c["theme"]);
Console.WriteLine(c["missing"]);
}
}Multiple Parameters
An indexer can take more than one parameter, ideal for matrices or 2D grids accessed as matrix[row, col].
using System;
class Matrix
{
private int[,] _data = new int[2, 2];
public int this[int row, int col]
{
get => _data[row, col];
set => _data[row, col] = value;
}
}
class Program
{
static void Main()
{
var m = new Matrix();
m[0, 0] = 1;
m[1, 1] = 9;
Console.WriteLine(m[0, 0] + ", " + m[1, 1]);
}
}Read-Only Indexers
Omit the setter for a read-only indexer, exposing data without allowing external modification.
using System;
class Fibonacci
{
public int this[int n]
{
get
{
int a = 0, bv = 1;
for (int i = 0; i < n; i++)
{
int t = a + bv;
a = bv;
bv = t;
}
return a;
}
}
}
class Program
{
static void Main()
{
var fib = new Fibonacci();
Console.WriteLine(fib[7]);
}
}Indexers vs Properties
A property is accessed by name (obj.Name); an indexer is accessed by key (obj[key]). Use an indexer when the object behaves like a collection.
using System;
class Inventory
{
private int[] _stock = new int[4];
public int Total => _stock.Length; // property
public int this[int slot] // indexer
{
get => _stock[slot];
set => _stock[slot] = value;
}
}
class Program
{
static void Main()
{
var inv = new Inventory();
inv[2] = 15;
Console.WriteLine("Slot 2: " + inv[2] + ", Total slots: " + inv.Total);
}
}Overloaded Indexers
You can define multiple indexers with different parameter types, and the compiler picks the matching one.
using System;
using System.Collections.Generic;
class People
{
private List<string> _names = new List<string> { "Ann", "Bob", "Cara" };
public string this[int i] => _names[i];
public int this[string name] => _names.IndexOf(name);
}
class Program
{
static void Main()
{
var p = new People();
Console.WriteLine(p[1]);
Console.WriteLine(p["Cara"]);
}
}Iterating an Indexed Object
Combine an indexer with a count property to loop over a custom collection naturally.
using System;
class Ring
{
private int[] _data = { 10, 20, 30 };
public int Count => _data.Length;
public int this[int i] => _data[i % _data.Length];
}
class Program
{
static void Main()
{
var ring = new Ring();
for (int i = 0; i < 5; i++)
Console.Write(ring[i] + " ");
Console.WriteLine();
}
}Putting It Together
Indexers make wrapper classes feel like native collections, hiding storage details behind familiar bracket syntax.
using System;
using System.Collections.Generic;
class Phonebook
{
private Dictionary<string, string> _book = new Dictionary<string, string>();
public string this[string name]
{
get => _book.TryGetValue(name, out var num) ? num : "unknown";
set => _book[name] = value;
}
}
class Program
{
static void Main()
{
var pb = new Phonebook();
pb["Alice"] = "555-1234";
Console.WriteLine("Alice: " + pb["Alice"]);
Console.WriteLine("Zed: " + pb["Zed"]);
}
}Quick Check
Test your understanding of indexers.
Recap
An indexer uses this[...] to give a class array-like access. It supports get/set, any parameter type (int, string, multiple), validation, overloading, and read-only forms. Use indexers for collection-like classes; use named properties for distinct attributes.
using System;
class Demo
{
private int[] _v = new int[3];
public int this[int i]
{
get => _v[i];
set => _v[i] = value;
}
}
class Program
{
static void Main()
{
var d = new Demo();
d[0] = 100;
Console.WriteLine(d[0]);
}
}Frequently asked questions
Is the “Indexers” lesson free?
Yes — the full text of “Indexers” is free to read here on the web, and the C# Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C# Academy course, upgrade to CoddyKit PRO.
What will I learn in “Indexers”?
Access objects with array-like syntax. You practise C# Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start C# Academy?
No prior experience is required. C# Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Indexers” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this C# Academy lesson?
Yes. Every C# Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.