- 7.1 Introduction
- 7.2 Packaging Code in C#
- 7.3 static Methods, static Variables and Class Math
- 7.4 Methods with Multiple Parameters
- 7.5 Notes on Using Methods
- 7.6 Argument Promotion and Casting
- 7.7 The .NET Framework Class Library
- 7.8 Case Study: Random-Number Generation
- 7.9 Case Study: A Game of Chance; Introducing Enumerations
- 7.10 Scope of Declarations
- 7.11 Method-Call Stack and Activation Records
- 7.12 Method Overloading
- 7.13 Optional Parameters
- 7.14 Named Parameters
- 7.15 C# 6 Expression-Bodied Methods and Properties
- 7.16 Recursion
- 7.17 Value Types vs. Reference Types
- 7.18 Passing Arguments By Value and By Reference
- 7.19 Wrap-Up
7.17 Value Types vs. Reference Types
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.17 shows an int variable named count that contains the value 7.
Fig. 7.17 | Value-type variable.
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 | 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.