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.



From Java to C#. A Developers Guide
From Java to C#: A Developers Guide
ISBN: 0321136225
EAN: 2147483647
Year: 2003
Pages: 221
Authors: Heng Ngee Mok

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net