C Sharp

Treating Objects Like Arrays by Using Indexers

In the "Arrays" section, you learned how to declare and instantiate arrays, how to work with the different array types, and how to iterate through the elements of an array. You also learned how to take advantage of some of the more commonly used properties and methods of the array types underlying the System.Array class. Let's continue working with arrays by looking at how a C#-specific feature called indexers enables you to programmatically treat objects as though they were arrays.-

And why would you want to treat an object like an array? Like most features of a programming language, the benefit of indexers comes down to making your applications more intuitive to write. In the first section of this chapter, "Properties as Smart Fields," you saw how C# properties give you the ability to reference class fields by using the standard class.field syntax, yet they ultimately resolve to getter and setter methods. This abstraction frees the programmer writing a client for the class from having to determine whether getter/setter methods exist for the field and from having to know the exact format of these methods. Similarly, indexers enable a class's client to index into an object as though the object itself is an array.

Consider the following example. You have a list box class that needs to expose some way in which a user of that class can insert strings. If you're familiar with the Win32 SDK, you know that to insert a string into a list box window, you send it a LB_ADDSTRING or LB_INSERTSTRING message. When this mechanism appeared in the late 1980s, we thought we really were object-oriented programmers. After all, weren't we sending messages to an object just like those fancy object-oriented analysis and design books told us to? However, as object-oriented and object-based languages such as C++ and Object Pascal began to proliferate, we learned that objects could be used to create more intuitive programming interfaces for such tasks. Using C++ and MFC (Microsoft Foundation Classes), we were given an entire lattice of classes that enabled us to treat windows (such as list boxes) as objects with these classes exposing member functions that basically provided a thin wrapper for the sending and receiving of messages to and from the underlying Microsoft Windows control. In the case of the CListBox class (that is, the MFC wrapper for the Windows list box control), we were given an AddString and an InsertString member function for the tasks previously accomplished by sending the LB_ADDSTRING and LB_INSERTSTRING messages.

However, to help develop the best and most intuitive language, the C# language design team looked at this and wondered, "Why not have the ability to treat an object that is at its heart an array, like an array?" When you consider a list box, isn't it just an array of strings with the additional functionality of displaying and sorting? From this idea was born the concept of indexers.