Overview
- Data is stored on the heap; a pointer to that data is stored on the stack.
- The heap gets cleaned by the garbage collector, removing objects that are no longer referenced.
- 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 best-known one.
Good practice
- Use String.Concat, String.Join, String.Format or a StringBuilder when working extensively with strings.
- See String Concatenation vs Memory Allocation for a 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

Exam 70-536 Study Notes
My study notes for Microsoft exam 70-536: .NET types, collections, generics, I/O, serialization and more, with C# examples.

Starting Exam 70-536 Study
After a burnout, I'm putting my own project on hold to study for Microsoft exam 70-536.

Design Patterns - Proxy Pattern
The Proxy Pattern, and the last article in the design patterns series, now that I've finished reading Head First Design Patterns.




