Value Types vs. Reference Types

Types in C# are divided into two categoriesvalue types and reference types. C#'s simple types are all value types. A variable of a value type (such as int) simply contains a value of that type. For example, Fig. 4.10 shows an int variable named count that contains the value 7.

Figure 4.10. Value type variable.

By contrast, a variable of a reference type (sometimes called a reference) contains the address of a location in memory where the data referred to by that variable is stored. Such a variable is said to refer to an object in the program. Line 11 of Fig. 4.8 creates a GradeBook object, places it in memory and stores the object's memory address in reference variable myGradeBook of type GradeBook as shown in Fig. 4.11. Note that the GradeBook object is shown with its courseName instance variable.

Figure 4.11. Reference type variable.

Reference type instance variables (such as myGradeBook in Fig. 4.11) are initialized by default to the value null. string is a reference type. For this reason, string variable courseName is shown in Fig. 4.11 with an empty box representing the null-valued variable in memory.

A client of an object must use a reference to the object to invoke (i.e., call) the object's methods and access the object's properties. In Fig. 4.8, the statements in Main use variable myGradeBook, which contains the GradeBook object's reference, to send messages to the GradeBook object. These messages are calls to methods (like DisplayMessage) or references to properties (like CourseName) that enable the program to interact with GradeBook objects. For example, the statement (in line 20 of Fig. 4.8)

myGradeBook.CourseName = theName; // set name using a property

uses the reference myGradeBook to set the course name by assigning a value to property CourseName. This sends a message to the GradeBook object to invoke the CourseName property's set accessor. The message includes as an argument the value "CS101 Introduction to C# Programming" that CourseName's set accessor requires to perform its task. The set accessor uses this information to set the courseName instance variable. In Section 7.11, we discuss value types and reference types in detail.

Software Engineering Observation 4 4

A variable's declared type (e.g., int, double or GradeBook) indicates whether the variable is of a value or a reference type. If a variable's type is not one of the thirteen simple types, or an enum or a struct type (which we discuss in Section 7.10 and Chapter 16, respectively), then it is a reference type. For example, Account account1 indicates that account1 is a variable that can refer to an Account object.

Категории