3

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);
TheLethalCoder
  • 6,668
  • 6
  • 34
  • 69
user2818430
  • 5,853
  • 21
  • 82
  • 148
  • 4
    You dont need to write `GetValue` and you know that the class is a collection with an indexer but you might lose readability because the indexer has no name, so don't misuse it. – Tim Schmelter Dec 14 '16 at 08:59
  • 2
    It's a *syntax sugar*, the advantage is *readability* – Dmitry Bychenko Dec 14 '16 at 09:01
  • @DmitryBychenko: readability isnt the benefit, the opposite can be true because the indexer has no name – Tim Schmelter Dec 14 '16 at 09:02
  • Exactly like what @DmitryBychenko said, it is actually just a syntactic sugar – oseme_techguy Dec 14 '16 at 09:04
  • My rule of thumb would be: If your class is basically just a collection (or wrapping one), use an indexer. ```names[0]``` is easily understood as 'the first name in a collection of names'. If the call-site cannot be read like that I'd avoid creating an indexer. YMMV – Benjamin Podszun Dec 14 '16 at 09:06

1 Answers1

7

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.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900