Pages

Men

rh

6/16/2012

Indexers in C#

Indexers:
The indexers are usually known as smart arrays in C# community. Defining a C# indexer is much like defining properties. We can say that an indexer is a member that enables an object to be indexed in the same way as an array.
this [argument list] 
{ 
    get 
    { 
        // Get codes goes here 
    } 
    set 
    { 
        // Set codes goes here 
    } 
}
The following program shows a C# indexer in action
// C#: INDEXER 
Using System; 
Using System.Collections; 
 
 
 
Class MyClass 
{ 
    Private string [] data = new string [5]; 
    Public string this [int index] 
    { 
       Get 
       { 
           return data[index]; 
       } 
       set 
       { 
           data[index] = value; 
       } 
    } 
}
 
Class MyClient 
{ 
   Public static void Main () 
   { 
      MyClass mc = new MyClass (); 
      mc [0] = "K1"; 
      mc[1] = "A3-126"; 
      mc[2] = "A22"; 
      mc[3] = "Navi"; 
      mc[4] = "Mumbai"; 
      Console.WriteLine("{0},{1},{2},{3},{4}",mc[0],mc[1],mc[2],mc[3],mc[4]); 
   } 
} 


No comments :

Post a Comment