blog

Home / DeveloperSection / Blogs / Indexer in C#

Indexer in C#

Amit Singh5237 25-Jan-2011

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

 


Updated 18-Sep-2014

Leave Comment

Comments

Liked By