All Pages All Books|
|
|||||
|
56 Chapter 2 • Introducing C# Programming
Understanding Properties and Indexers
Two of the more interesting features of C# are properties and indexers. Properties allow you to call methods on a class using syntax that indicates you are accessing member variables. Indexers allow you to access collections within a class using array syntax. You will see examples of each in the following sections.
Using Properties
If you come from a C++ background, you have probably written many get and set methods for classes you have created. A typical pattern used by C++ programmers is to make member variables of a class private and provide public accessor methods to assign and retrieve the values of the member variables. A public set method is written to assign a value to a member variable, and a get method is written to retrieve the value assigned to a member variable. An alternate solution is to make the member variables themselves public. The advantage of using get and set methods is that if the underlying data type ever changes, the consumer of the class does not have to change his code. Only the get and set methods need to be rewritten. This is often referred to as data hiding.
Using get and set methods has a couple of disadvantages. First, it seems a little more intuitive to just assign a value to a data member or retrieve its value rather than having to use accessor methods. Also, slightly less typing is involved in accessing the data member directly.
C# provides the best of both methods. It supports the idea of properties. Properties are method calls that look like direct access to member data. Figure 2.5 is a complete listing that shows properties in action. The program is included on the CD in the file Properties.cs.
Note__________________________________________________
|
|||||
|
|
|||||
|
Throughout the rest of the chapter, we expand on this example of an employee list.
|
|||||
|
|
|||||
|
i
|
Figure 2.5 The Properties.cs Program Listing
using System; /// <summary>
|
||||
|
|
|||||
|
Continued
|
|||||
|
|
|||||
|
|
|
||||
|
|
|||||
All Pages All Books