Table of Contents
Introduction
Value Types
Reference Types
In contrast to value types, the value of a reference types is allocated on the heap. Another name for a reference type, that you might be more familiar with, is an object. Reference types stores the reference to the data, unlike value types, that stores the value. To demonstrate the difference between a reference type and a value type, let’s look at this example:
using System;
public class Cat
{
private int age;
public void SetAge(int years)
{
age = years;
}
public int GetAge()
{
return age;
}
}
public class RefTest
{
public static void Main()
{
Cat miranda = new Cat();
miranda.SetAge(6);
Cat caesar = miranda; //caesar now equals miranda
Console.WriteLine("Caesar: " + caesar.GetAge());
Console.WriteLine("Miranda: " + miranda.GetAge());
miranda.SetAge(10); //change Miranda's age, what happen to Caesar now?
Console.WriteLine("Caesar: " + caesar.GetAge());
Console.WriteLine("Miranda: " + miranda.GetAge());
Console.WriteLine(caesar == miranda);
}
}
Output:
Caesar: 6 Miranda: 6 Caesar: 10 Miranda: 10 True
To compile this code (if you downloaded it), type:
csc ReferenceType.cs
A class is a reference type, and in the example above I create the class Cat.
As you can see, we do not in any way alter caesar’s age. Despite this, the age is the same as miranda’s! This is actually how it is supposed to be, they are “sharing” the same memory. Or, they reference the same data. When we alter the value for one of them, the other will get the same value. The last line verifies that they are the same. We are using the == operator (two equal signs) to check this, and it returns true. We could have also used
Console.WriteLine(Object.ReferenceEquals(caesar, miranda));
to check if they referenced the same memory space.
A picture of this would look like:

For a value type, we do not have this behavior, because in this case the value would have been copied instead of the reference to the value.
Memory for variables that are reference types are not automatically freed when they go out of scope. Instead the Garbage Collector is responsible for this.
In contrast to value types, a reference type does not necessarily have a value. It can be null. This means that the variable does not reference any data.
Cat caesar;
In the above code, caesar does not have a value, and is null.
[ 1 ] [ 2 ] [ Next ]