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

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.