O'Reilly logo

From Java to C#: A Developer's Guide by Heng Ngee Mok

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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: ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required