Thursday, May 26, 2016

Indexers in C#

In today's blog post, we will understand the indexers in C#. Indexers are a useful and less-known feature of C#.

Indexers in C#

An indexer is a way to overload the indexing operator (just like we access array's elements). By defining an indexer on a class, we can access it's properties using an index. Let's take a look at an example to understand how it's done.




Indexers in C#


Suppose we have a Vector class like this:

public class Vector
{
    public int X { get; set; }
    public int Y { get; set; }

    public int this[int index]
    {
        get
        {
            switch (index)
           {
                 case 0: return X;
                 case 1: return Y;
                 default: throw new IndexOutOfRangeException();
           }
        }

        set
        {
            switch (index)
            {
                case 0: X = value;
                    break;
                case 1: Y = value;
                    break;
                default: throw new IndexOutOfRangeException();
            }
        }

    }

}

So here we defined integer indexer in the class. Please note the syntax how we used the "this" keyword with "int index" parameter. Inside the method definition we have the get and set, so we can get the property as well as set the property using integer index.

We are not just limited to integer index. We can even have string indexer like this:


public int this[string index]
{
     get
     {
        switch (index)
        {
              case "x": return X;
              case "X": return X;
              case "y": return Y;
              case "Y": return Y;
              default: throw new IndexOutOfRangeException();
        }

     }

     set
     {
          switch (index)
          {
              case "x":
              case "X":
                  X = value;
                  break;
              case "y":
              case "Y":
                   Y = value;
                   break;
              default: throw new IndexOutOfRangeException();
          }
     }

Please note the "string index" parameter this time. Inside it we define what to do in case of "x" or "X" and "y" or "Y".
Now, let's take a look at how we can use these integer as well as string indexers:

static void Main(string[] args)
{
      var vector1 = new Vector();
      vector1[0] = 2; // integer indexer
      vector1[1] = 3;

      //string indexer
      Console.WriteLine("Vector 1: X = {0}, Y = {1}",
                   vector1["X"], vector1["Y"]);
      Console.ReadLine();
}

So we saw how they can add to readability of the code. Using indexers, we can access each of the property like we are accessing the array elements.

Conclusion

So we saw how to define integer as well as string indexers on a class. Just because we can define indexers doesn't mean it's always the right solution. If it increases the readability of the code and makes sense then only we should use them. In our example, for Vector class it makes it easy to read the code.

For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)


No comments:

Post a Comment