capypad
0 day streak
csharp / intermediate
Snippet

Accessing Objects via Custom Indexers

Indexers allow instances of a class or struct to be indexed just like arrays. This is useful for classes that represent a collection of data or provide access to internal buffers.

snippet.csharp
csharp
1
2
3
4
5
6
7
8
9
public class SimpleCache
{
private string[] _data = new string[10];
public string this[int index]
{
get => _data[index];
set => _data[index] = value;
}
}
Breakdown
1
this[int index]
The 'this' keyword is used to define an indexer. The parameter inside the brackets determines the index type.
2
get => / set =>
Like properties, indexers use accessors to retrieve or assign values to the indexed data.