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

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