What are the benefits of an indexer?

150 views Asked by At

Can somebody explain what is the benefit of having an indexer?

public class MyClass
{
    private List<string> list = new List<string>()

    public string this[int value]
    {
         get 
         {
             return list[value];
         }
     }

     public string GetValue(int value)
     {
          return list[value];
     }
}

What is the benefit of using:

MyClass target = new MyClass();
string value = target[0];

over this:

MyClass target = new MyClass();
string value = target.GetValue(0);
1

There are 1 answers

0
Marc Gravell On BEST ANSWER

It is purely syntactic convenience and readability / expressiveness. It is still implemented as a method. So: if you think target[0] is more obvious, convenient and readable for your scenario: use an indexer.