How do I overload the [] operator in C#

C#Operator OverloadingIndexer

C# Problem Overview


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];
}

C# Solutions


Solution 1 - C#

public int this[int key]
{
    get => GetValue(key);
    set => SetValue(key, value);
}

Solution 2 - C#

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]);
    }
}

Solution 3 - C#

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]
...

Solution 4 - C#

public int this[int index]
{
    get => values[index];
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAdam TegenView Question on Stackoverflow
Solution 1 - C#Florian GreinacherView Answer on Stackoverflow
Solution 2 - C#William BrendelView Answer on Stackoverflow
Solution 3 - C#Jeff YatesView Answer on Stackoverflow
Solution 4 - C#BFreeView Answer on Stackoverflow