Implementing an Indexer
The next step is to implement an indexer so that we can treat the BeerInventory object like an array of Beer ojects. An indexer is an indexable property named this. The easiest way to create an indexer is to use the Class View explorer in Visual Studio .NET.
To open the Class View explorer, select View, Class View in Visual Studio .NET and expand the Project node (see Figure 1) and the namespace node until you see the BeerInventory class node. Right-click the BeerInventory class node and select Add, Add Indexer from the context menu. Fill in the Indexer Wizard as shown in Figure 2, indicating that the indexer return type is Beer and the indexer variable is named index. The indexer property shown in the updated implementation of BeerInventory will be added to the class, shown in Listing 3.
Figure 1 Use the Class View explorer to add elements to your classes, like the indexer shown in Listing 3.
Figure 2 Creating the indexer method for BeerInventory.
Listing 3Add an Indexer to the BeerInventory Class
public class BeerInventory : System.Collections.CollectionBase { public static BeerInventory CreateTestInventory() { BeerInventory inventory = new BeerInventory(); inventory.Add(new Beer("Hamms", "Hamms Brewing Co.", 3)); inventory.Add(new Beer("Budweiser", "Anheuser-Busch", 1000)); inventory.Add(new Beer("Mulholland Rain", "City Brewers", 113)); return inventory; } public int Add(Beer value) { return List.Add(value); } public Beer this[int index] { get { return (Beer)List[index]; } set { List[index] = value; } } }
The indexer is the last part of the class. Note the special use of the word this. Now when you index BeerInventory, you can treat an instance as if it were an array. For example, assume you had an instance of BeerInventory named inventory; writing inventory[0] would return the Beer object at index 0.
I also sneaked in the CreateTestInventory factory method to show you what that might look like, and an Add method. The Visual Studio .NET help doesn't require you to implement a specific Add method, but I discovered that you'll need the Add method if you want to return strongly typed arrays from Web services. (A helpful hint if you intend to implement a Web service that returns a strongly typed collection.)