21.1 Overloading indexers


You can have multiple overloaded indexers in the same class to enable access to the private array in other ways. There's a rule though “ indexers must take in at least one parameter. Under special circumstances, you may choose to let your indexer take in multiple parameters.

Let's change TestClass a bit.

 1: class TestClass{  2:     // this is the encapsulated array  3:     string[] MyArray = new string[10];  4:  5:     // constructor  6:     public TestClass(){  7:         for (int i=0; i<10; i++){  8:             MyArray[i] = "uninitialized";  9:         } 10:     } 11: 12:     // here's where the magic works 13:     public string this[int index]{ 14:       get{ 15:         return MyArray[index]; 16:       } 17:       set{ 18:         MyArray[index] = value; 19:       } 20:     } 21: 22:     // overloaded indexer method 23:  public int this[string s]{  24:  get{  25:  for (int i  =  0; i<10; i  ++  ){  26:  if (MyArray[i].Equals(s))  27:  return i;  28:  }  29:  return -1;  30:  }  31:  }  

I have inserted an overloaded indexer into TestClass that takes in a string, and which contains only the get section. What this overloaded indexer does is to check through MyArray for the first occurrence of the string passed in and returns the index value of the first match. The indexer returns -1 if none of the array elements contains a matching string.

Main() is rewritten to try out this new indexer.

 32: 33:     public static void Main(string[] args){ 34: 35:       TestClass c = new TestClass(); 36: 37:       // assigning values to MyArray of c 38:       c[2] = "hello"; 39:       c[3] = "hello"; 40:       c[5] = "hello"; 41: 42:       // invoke the overloaded indexer 43:       Console.WriteLine ("The first index which "+             "contains the string hello is "+  c["hello"]  ); 44:     } 45: } 

Output:

 c:\expt>test This first index which contains hello is 2 

It seems that the overloaded indexer is working fine.



From Java to C#. A Developers Guide
From Java to C#: A Developers Guide
ISBN: 0321136225
EAN: 2147483647
Year: 2003
Pages: 221
Authors: Heng Ngee Mok

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net