7.17 Value Types vs. Reference Types

Types in C# are divided into two categories—value types and reference types.

Value Types

C#’s simple types (like int, double and decimal) are all value types. A variable of a value type simply contains a value of that type. For example, Fig. 7.18 shows an int variable named count that contains the value 7.

Fig. 7.18 Value-typd variable.

Reference Types

By contrast, a variable of a reference type (also called a reference) contains the location where the data referred to by that variable is stored. Such a variable is said to refer to an object in the program. For example, the statement


Account myAccount = new Account();

creates an object of our class Account (presented in Chapter 4), places it in memory and stores the object’s reference in variable myAccount of type Account, as shown in Fig. 7.19. The Account object is shown with its name instance variable.

Reference-Type Instance Variables Are Initialized to null by Default

Reference-type instance variables (such as myAccount in Fig. 7.19) are initialized by default to null. The type string is a reference type. For this reason, string instance variable name is shown in Fig. 7.19 with an empty box representing the null-valued variable. A string variable with the value null is not an empty string, which is represented by "" or string.Empty. Rather, the value null represents a reference that does not refer to an object, whereas the empty string is a string object that does not contain any characters. In Section 7.18, we discuss value types and reference types in more detail.

Fig. 7.19 Reference-type variable.

Software Engineering Observation 7.5

A variable’s declared type (e.g., int or Account) indicates whether the variable is of a value type or a reference type. If a variable’s type is one of the simple types (Appendix B), an enum type or a struct type (which we introduce in Section 10.13), then it’s a value type. Classes like Account are reference types.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset