One of the key aspects of object-oriented design is the grouping of data to provide structure. This section discusses how to add data to the Employee class. The general object-oriented term for a variable that stores data within a class is member variable. This term is well understood in C#, but the more standard term—and the one used in the specification—is field, which is a named unit of storage associated with the containing type. Instance fields are variables declared at the class level to store data associated with an object. Hence, association is the relationship between the field data type and the containing field.
In Listing 6.4, the class Employee has been modified to include three fields: FirstName, LastName, and Salary.
With these fields added, it is possible to store some fundamental data with every Employee instance. In this case, you prefix the fields with an access modifier of public. The use of public on a field indicates that the data within the field is accessible from classes other than Employee (see the “Access Modifiers” section later in this chapter).
Like a local variable declaration, a field declaration includes the data type to which the field refers. Furthermore, it is possible to assign fields an initial value at declaration time, as demonstrated with the Salary field in Listing 6.5.
We delay the guidelines of naming and coding fields until later in the chapter, after C# properties and constructors have been introduced. Suffice it to say, until then the listings frequently do not follow the standard coding guidelines. In fact, there is a preponderance of the following warnings:
In this case, since FirstName and LastName are not initialized, they trigger the CS8618 warning.
For purposes of elucidation, these warnings are ignored and, in fact, disabled with #pragma directives in the accompanying source code until the concepts are fully developed later in the chapter.
You can set and retrieve the data within fields. However, the fact that a field does not include a static modifier indicates that it is an instance field. You can access an instance field only from an instance of the containing class (an object). You cannot access it from the class directly (without first creating an instance, in other words).
Listing 6.6 shows an updated look at the Program class and its utilization of the Employee class, and Output 6.1 shows the results.
Listing 6.6 instantiates two Employee objects, as you saw earlier. It then sets each field, calls IncreaseSalary() to change the salary, and displays each field associated with the object referenced by employee1.
Notice that you first have to specify which Employee instance you are working with. Therefore, the employee1 variable appears as a prefix to the field name when assigning and accessing the field.