Value Types and Reference Types in .net 3.5

Before examining the data types in C#, it is important to understand that C# distinguishes between two categories of data type:

 

1.        Value types

2.        Reference types

 

Conceptually, the difference is that a value type stores its value directly, whereas a reference type stores a reference to the value.


Value types in C# are basically the same as simple types (integer, float, but not pointers or references) in Visual Basic or C++.


Reference types are the same as reference types in Visual Basic and are similar to types accessed through pointers in C++.

 

These types are stored in different places in memory; value types are stored in an area known as the stack , and reference types are stored in an area known as the managed heap . It is important to be aware of whether a type is a value type or a reference type because of the different effect each assignment has.

 

For example, int is a value type, which means that the following statement will result in two locations in memory storing the value 20:

 

// i and j are both of type int

 

i = 20;

j = i;

 

However, consider the following code. For this code, assume that you have defined a class called Vector . Assume that Vector is a reference type and has an int member variable called Value :

 

Vector x, y;

x = new Vector();

x.Value = 30; // Value is a field defined in Vector class

y = x;

Console.WriteLine(y.Value);

y.Value = 50;

Console.WriteLine(x.Value);

 

The crucial point to understand is that after executing this code, there is only one Vector object around. x and y both point to the memory location that contains this object. Because x and y are variables of a reference type, declaring each variable simply reserves a reference — it doesn ' t instantiate an object of the given type.


This is the same as declaring a pointer in C++ or an object reference in Visual Basic. In neither case is an object actually created. In order to create an object, you have to use the new keyword, as shown. Because x and y refer to the same object, changes made to x will affect y and vice versa. Hence the code will display 30 then 50 .

 

If a variable is a reference, it is possible to indicate that it does not refer to any object by setting its value to null:

 

y = null;

 

This is the same as setting a reference to null in Java, a pointer to NULL in C++, or an object reference in  Visual Basic to Nothing . If a reference is set to null , then clearly it is not possible to call any nonstatic member functions or fields against it; doing so would cause an exception to be thrown at runtime.

Next Recommended Reading New Features in .NET 3.5