Книга: C# 2008 Programmer
Reference Types
Reference Types
For reference types, the variable stores a reference to the data rather than the actual data. Consider the following:
Button btn1, btn2;
btn1 = new Button();
btn1.Text = "OK";
btn2 = btn1;
Console.WriteLine("{0} {1}", btn1.Text, btn2.Text);
btn2.Text = "Cancel";
Console.WriteLine("{0} {1}", btn1.Text, btn2.Text);
Here, you first declare two Button controls — btn1
and btn2
. btn1
's Text
property is set to "OK
" and then btn2
is assigned btn1
. The first output will be:
OK OK
When you change btn2
's Text property to "Cancel
", you invariably change btn1
's Text
property, as the second output shows:
Cancel Cancel
That's because btn1
and btn2
are both pointing to the same Button object. They both contain a reference to that object instead of storing the value of the object. The declaration statement (Button btn1, btn2;
) simply creates two variables that contain references to Button
objects (in the example these two variables point to the same object).
To remove the reference to an object in a reference type, simply use the null
keyword:
btn2 = null;
When a reference type is set to null, attempting to access its members results in a runtime error.
Value Types versus Reference Types
For any discussion about value types and reference types, it is important to understand how the .NET Framework manages the data in memory.
Basically, the memory is divided into two parts — the stack and the heap. The stack is a data structure used to store value-type variables. When you create an int variable, the value is stored on the stack. In addition, any call you make to a function (method) is added to the top of the stack and removed when the function returns.
In contrast, the heap is used to store reference-type variables. When you create an instance of a class, the object is allocated on the heap and its address is returned and stored in a variable located on the stack.
Memory allocation and deallocation on the stack is much faster than on the heap, so if the size of the data to be stored is small, it's better to use a value- type variable than reference-type variable. Conversely, if the size of data is large, it is better to use a reference-type variable.
C# supports two predefined reference types — object
and string
— which are described in the following table.
C# Type | .NET Framework Type | Descriptions |
---|---|---|
object |
System.Object |
Root type from which all types in the CTS (Common Type System) derive |
string |
System.String |
Unicode character string |
Chapter 4 explores the System.Object
type, and Chapter 8 covers strings in more detail.