Types in C# are divided into two categories—value types and reference 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
.
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.
null
by DefaultReference-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.
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.