Indexers in C#

In this blog we will discuss about the Indexers in c#.

  • Indexers in c# are location indicators and are used to access the class objects, just like accessing elements in an array.
  • They are useful in cases where a class is a container of other objects.

An indexer in c# looks like a property and is written in the same way as a property, but with two differences:

  1. The indexer takes an index argument and looks like an array.
  2. The indexer is declared using the name this.
  3. The indexer is implemented through get and set accessors. Example

General syntax for Indexers in c#:

public double this [ int idx ]
{
  get
   {
     //return the desired data
   }
  set
   {
    //set the desired data
   }
}

  • The implementation rules for get and set accessors are the same as properties.
  • The return type decides what will be returned.
  • The parameter inside the square brackets is used as an index.In the above example ,we have used an int, but it can be any object type

code:

using System;
using System.Collections;
class List
{
   ArrayList array = new ArrayList();
   public object this [ int index ]
   {
     get
      {
         if ( index < 0  || index   >= array.Count )
          {
             return null;
          }
         else
          {
             return ( array[index] );
          }
      }
     set
      {
             array[index]  = value;
      }
   }
}
class IndexerTest
{
   public static void Main ()
    {
        List list = new List ();
        list[0] = "123";
        list[1] = "abc";
        list[1] = "xyz"; 
        for ( int i = 0; i<list.Count ; i++ )
           Console.WriteLine( list[i] );
    }
}

Indexers are sometimes referred to as smart arrays.As we discussed earlier indexers are similar to properties bur different in the following cases alone which are listed below.

  • A property can be a static member, whereas an indexer is always an instance member.
  • A get accessor of a property corresponds to a method with no parameters, whereas a get accessor of a indexer corresponds to a method with the same formal parameter list as a indexer.
  • A set accessor of a property corresponds  to a method with a single parameter named value,whereas a set accessor method of a indexer corresponds to a method with the same formal parameter list as the indexer, plus the parameter named value.
  • It is an error for an indexer to declare a local variable with the same name as an indexer parameter

Leave a Comment

Your email address will not be published. Required fields are marked *