An indexer is worked as properties. Indexers allow instancesof a class or struct to be indexed just like arrays. Indexers are also calledsmart arrays in C# and can be used to treat an object as an array.

Syntax for an indexer declaration

Modifier  returnType this[argument]

Some point for indexers

·        Indexers concept is object act as an array.

·        thiskeyword is used to define the indexers.

·        A get accessor returnsa value and A set accessor assigns a value.

·        Indexers cannot be static.

·        Indexers can be abstract. There would be no codeinside it in such a case.

·        The return type can be any valid C# types

For example:

This is thesimple example how use the indexers in c#

class Program
{
   static void Main(string[]args)
   {
         yyya = new yyy();
         a[1] = 24;          
   }
}
public class yyy
{
   public int this[int i]
   {
      set
      {
          Console.WriteLine("The value of array a[" + i + "]: " + value);
          Console.ReadLine();
       }
   }
}


Output:

The value of array a[1]: 24

 

  Modified On Sep-18-2014 01:23:54 PM

Leave Comment