339

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

4 Answers 4

886
public int this[int key]
{
    get => GetValue(key);
    set => SetValue(key, value);
}
Sign up to request clarification or add additional context in comments.

5 Comments

Why is it that every time I need to implement an index operator, I have to look it up? And each time I end up on this answer... wish I could vote it up multiple times :)
This is so super awesome. Can it be done in an interface? interface ICache { object this[string key] { get; set; } } Edit: Yes.
dont know why they chose to omit the word 'operator' in this declaration - thats the mistake I always make! Nice answer
Michael: You should probably be using generics: interface ICache<TContent> { TContent this[string key] { get; set; } }.
You can also use multi dimensional array public int this[int x, int y]
70

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

Comments

37

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

1 Comment

And don't forget you can have any combination of types for multiple indexers....
12
public int this[int index]
{
    get => values[index];
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.