Reference Types
Part of my 2008 study notes for exam 70-536 (.NET Framework 2.0).
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
- Use String.Concat, String.Join, String.Format or a StringBuilder when excessively working with strings.
- See String Concatenation vs Memory Allocation for detailed analysis of string operations.
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());
You May Also Like
ArrayList Class
Resizeable, unordered, index-based collection. Suffers from boxing/unboxing when working with value types. Implements IEnumerator, allowing foreach…
BinaryReader Class and BinaryWriter Class
Used to read and write binary data from streams. Call the correct Read methods when using a BinaryReader.
BitArray Class
Contains an array of true/false values. Resizable through the Length property. Supports bitwise operations.



