Home > DeveloperSection > Blogs > Indexer in C#

Indexer in C#


C# C# 
Ratings:
0 Comment(s)
 2671  View(s)
Rate this:

Indexer in C#

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

 

 


Don't want to miss updates? Please click the below button!

Follow MindStick