.NET Framework Reference types in use


Reference types are comprised of both a reference to a memory area, and a value stored within that area.
This is analogous to pointers in C/C++.

All reference types are stored on what is known as the heap.
The heap is simply a managed area of memory where objects are stored. When a new object is instantiated, a part of the heap will be allocated for use by that object, and a reference to that location of the heap will be returned. The heap is managed and maintained by the garbage collector, and does not allow for manual intervention.

In addition to the memory space required for the instance itself, additional space is required to store the reference itself, along with additional temporary information required by the .NET CLR.

The code below demonstrates a reference type being assigned to a new variable. In this instance, we are using a class, all classes are reference types (even if static).

When a reference type is assigned to another variable, it is the reference to the object that is copied over, not the value itself. This is an important distinction between value types and reference types.

The implications of this are that we now have two references to the same object.
Any changes to the values within that object will be reflected by both variables.

class PersonAsReferenceType
    public string Name;

class Program
    static void Main()
        PersonAsReferenceType personA;

        personA = new PersonAsReferenceType { Name = "Bob" };

        var personB = personA;

        personA.Name = "Linda";

        Console.WriteLine(               // Outputs 'True' - because
            object.ReferenceEquals(      // personA and personB are referencing 
                personA,                 // the *same* memory location

        Console.WriteLine(personA.Name); // Outputs 'Linda'
        Console.WriteLine(personB.Name); // Outputs 'Linda'