Chapter 21. C indexes


Chapter 21. C# indexes

I recommend that you complete Chapter 20 before starting on indexes. Indexes are somewhat similar to properties.

Like a C# property, a C# index is a new programming feature embedded into the language to help developers to be more efficient. Indexers enable an instance of a class, which has an array as a field, to be treated like an array itself.

Study the example below.

 1: class TestClass{  2:     // this is the array field  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:     // here's where the magic works 12:  public string this[int index]{  13:  get{  14:  return MyArray[index];  15:  }  16:  set{  17:  MyArray[index]  =  value;  18:  }  19:  }  20: 21:     public static void Main(string[] args){ 22: 23:       TestClass c = new TestClass(); 24: 25:       // assigning values to MyArray of c 26:  c[2]  =  "indexers";  // set 27:  c[3]  =  "are";  // set 28:  c[5]  =  "convenient";  // set 29: 30:       // extracting values from MyArray 31:       for (int i=0; i<10; i++){ 32:         System.Console.WriteLine(i +" "+  c[i]  ); //get 33:       } 34:     } 35: } 

Output:

 C:\expt>test 0 uninitialized 1 uninitialized 2 C# 3 is 4 uninitialized 5 powerful 6 uninitialized 7 uninitialized 8 uninitialized 9 uninitialized 

As you can see, the indexed class encapsulates a private array which it exposes to the external world via a public indexer. There is a special method in TestClass called this (lines 12 “ 19), which is declared as public string this[int index] . This special method contains get and set sections which execute automatically when the indexer is used (lines 26 “ 28, and 32 respectively). Lines 26 “ 28 set the values in elements 2, 3, and 5 via the indexer, and line 32 gets the values of each array element iteratively for printing out.

In this example, this takes an int but, like any other method, it can take in anything (but at least one parameter). This indexer method is usually declared as a public method so that external classes can invoke it, but that is not compulsory.

Like properties, you can omit either the set or get section within an indexer declaration (the this method) but you cannot omit both. Indexers with only a get section cannot be set via the indexer, and vice versa.



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