How do I overload the [] operator in C#
public int this[int key]
{
get => GetValue(key);
set => SetValue(key, value);
}
I believe this is what you are looking for:
Indexers (C# Programming Guide)
class SampleCollection<T>
{
private T[] arr = new T[100];
public T this[int i]
{
get => arr[i];
set => arr[i] = value;
}
}
// This class shows how client code uses the indexer
class Program
{
static void Main(string[] args)
{
SampleCollection<string> stringCollection =
new SampleCollection<string>();
stringCollection[0] = "Hello, World";
System.Console.WriteLine(stringCollection[0]);
}
}
The [] operator is called an indexer. You can provide indexers that take an integer, a string, or any other type you want to use as a key. The syntax is straightforward, following the same principles as property accessors.
For example, in your case where an int
is the key or index:
public int this[int index]
{
get => GetValue(index);
}
You can also add a set accessor so that the indexer becomes read and write rather than just read-only.
public int this[int index]
{
get => GetValue(index);
set => SetValue(index, value);
}
If you want to index using a different type, you just change the signature of the indexer.
public int this[string index]
...