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

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

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