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 in TestClass which takes in the current year and returns the difference between the current year and the value stored in the MyBirthYear field. There is no good reason for you to use an indexer in this case.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.254.22