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

Get From Java to C#: A Developer's Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.