21.2. Wrong use of indexers

It is possible (but incorrect) to use indexers to retrieve a private field. You should use properties or accessor methods to do that. Indexers only make sense when a class encapsulates an array, and there is an array-like abstraction. Examine this negative example.

 1: class TestClass{
 2:   private int MyBirthYear = 1975;
 3:
 4:   public int this[int currentYear]{
 5:     get{
 6:       return currentYear – MyBirthYear;
 7:     }
 8:   }
 9:
10:   public static void Main(string[] args){
11:     TestClass c = new TestClass();
12:     System.Console.WriteLine ("Age is " + c[2002]);
13:   }
14: }

Output:

c:\expt>test
Age is 27

The program above works but makes use of indexes in a fanciful and unrecommended way. You could have written a getAge() method ...

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.