C# for Java Programmers

Indexers are an interesting technique in C# that permits your classes to be treated as arrays. This feature is not found in Java. It is a very handy technique if you have an object that can reasonably be thought of as an array. However, it is not recommended that you give every object this capability. For example, if we were going to make a class to represent a deck of cards, it would make sense to use indexers for the cards themselves, but there would not be a need to use indexers for the whole deck. We will actually expound on this example in the upcoming sections.
Although this is a powerful ability, it is not difficult to implement. Internally it uses a special kind of property with get and set accessor methods to specify its behavior. Properties will be discussed in Chapter 7.
Imagine we had a class to represent a playing card deck. It would make sense that we should be able to treat this deck as an array of 52 playing cards. To define an indexer we need to add the this [] property to our class, as well as its return type. The following code snippet does this.
private String[] Cards = new String[52];<b class="bold"> public String this [int index]</b> <b class="bold">{ get { return Cards[index]; } set { Cards[index] = value;