Indexers in C#
Short, interview-ready summary.
What is an Indexer?
An indexer lets an object be indexed like an array using [ ] syntax. Instead of calling GetItem(0), you write obj[0].
Memory hook
"Indexer = this[key] — make your type indexable like array or Dictionary"
Basic syntax
public class MyCollection
{
private readonly string[] _items = new string[10];
// Indexer: object[key]
public string this[int index]
{
get => _items[index];
set => _items[index] = value;
}
}
var col = new MyCollection();
col[0] = "hello";
string s = col[0];
- this[...] — indexer declaration
- get / set — accessors (can be read-only with get only)
- Parameter — usually
int(array-like) orstring(dictionary-like); can have multiple params
Multiple parameters
public class Matrix
{
private readonly int[,] _data = new int[10, 10];
public int this[int row, int col]
{
get => _data[row, col];
set => _data[row, col] = value;
}
}
var m = new Matrix();
m[2, 3] = 42;
String (or other type) as key
public class DataStore
{
private readonly Dictionary<string, string> _data = new();
public string this[string key]
{
get => _data.TryGetValue(key, out var v) ? v : null;
set => _data[key] = value;
}
}
var store = new DataStore();
store["name"] = "Alice";
Indexer vs property vs method
| Feature | Indexer | Property | Method |
|---|---|---|---|
| Name | this[...] | Named (e.g. Count) | Named (e.g. GetItem) |
| Parameters | Required (key/index) | None | Optional |
| Access | obj[key] | obj.Count | obj.GetItem(0) |
- Use indexer when the type is logically a collection or map and indexing is natural.
- Use property for a single, named value.
- Use method when you need logic beyond simple get/set or multiple overloads with different semantics.
Read-only indexer
public string this[int index] => _items[index];
- No
set— assignment likeobj[0] = "x"is not allowed.
Common use cases
- Custom collection — wrap array or list; expose
[i] - Dictionary-like access — key-value by
[key] - Matrix / grid —
[row, col] - Configuration —
config["SettingName"]
Interview one-liner
"An indexer lets an object be indexed with [ ] like an array or dictionary. It's declared with this[params] and has get/set accessors. Use it when your type is naturally indexable (collection, map, matrix)."
Cheat sheet
this[key] = indexer; get/set accessors
Parameter = int, string, or multiple (e.g. row, col)
Read-only = get only, no set
Use when type is logically indexable