Reference Types

Overview

  • Data stored on the heap, a pointer to that data is stored on the stack.
  • The heap gets cleaned by the garbage collector, removing items which don't have a reference to it anymore.
  • Copying reference types will only copy the pointer, not duplicate the data.
    • This means altering a reference type through one variable will also be reflected when accessing it through another variable, pointing at the same heap location.
  • Reference types can be immutable, System.String being the most known one.

Good practice

Examples

Value types vs Reference types

// ---------------------------------------------------------------------------------------------
// Example of reference types.
// ---------------------------------------------------------------------------------------------
 
MyNumber a, b;
a = new MyNumber(5); // Store 5 in a
b = a;               // Copy the reference to 'MyNumber' a into b
a.X = 10;            // Modify a, but since b is pointing to the same object, b will change too
 
Console.WriteLine(a.X); // Will print 10
Console.WriteLine(b.X); // Will print 10
class MyNumber
{
    private int _x;
 
    public int X
    {
        get { return this._x; }
        set { this._x = value; }
    }
 
    public MyNumber(int x)
    {
        this._x = x;
    }
}

Strings

string[] words = new string[] { "Word1", "Word2", "Word3" };
Console.WriteLine(String.Join(" | ", words)); // Word1 | Word2 | Word3
Console.WriteLine(String.Concat(words));      // Word1Word2Word3
 
StringBuilder longString = new StringBuilder();
longString.Append("Hello World");
Console.WriteLine(longString.ToString());