How do I overload the [] operator in C#

Adam Tegen picture Adam Tegen · Jan 8, 2009 · Viewed 139.8k times · Source

I would like to add an operator to a class. I currently have a GetValue() method that I would like to replace with an [] operator.

class A
{
    private List<int> values = new List<int>();

    public int GetValue(int index) => values[index];
}

Answer

Florian Greinacher picture Florian Greinacher · Jan 8, 2009
public int this[int key]
{
    get => GetValue(key);
    set => SetValue(key, value);
}