Home > Articles

This chapter is from the book

This chapter is from the book

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.17 shows an int variable named count that contains the value 7.

Fig. 7.17

Fig. 7.17 | Value-type 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.18. The Account object is shown with its name instance variable.

Fig. 7.18

Fig. 7.18 | Reference-type variable.

Reference-Type Instance Variables Are Initialized to null by Default

Reference-type instance variables (such as myAccount in Fig. 7.18) 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.18 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.

  • + Share This
  • 🔖 Save To Your Account