What’s the Stack? What’s the Heap?

Those are great interview questions. Every developer should know how to answer them, because you can’t write code correctly without understanding the Stack and the Heap, what they do, and how they interrelate.

Am I going to explain it here? I could, but I found a terrific exposition on it. So I’ll just point you there.

C# Heap(ing) Vs Stack(ing) in .NET: Part 1
C# Heap(ing) Vs Stack(ing) in .NET: Part 2
C# Heap(ing) Vs Stack(ing) in .NET: Part 3
C# Heap(ing) Vs Stack(ing) in .NET: Part 4

The main implication is that value types (things like int, bool, enums, structs) are allocated on the Stack, while reference types (classes, arrays, delegates) are allocated on the Heap. Objects on the Heap are basically singletons. In other words, once an object is created (using new), all variables assigned the object are simply pointers to the object. Let’s say you set a property on one variable. Getting that same data from a property from another variable will reflect the new value.

// Classes are reference types
class
Person
{

  public string Name;
  public Person(string name)
  {
    Name = name;
  }
}

static void Main()
{
  // Create a new Person on the Heap
Person p1 = new Person("Tony");

  // p1 and p2 both point to the same object
Person p2 = p1;

  // Change name via p2
  p2.Name = "Zuzana";

  // p1’s name is now Zuzana
Debug.Assert(p1.Name == "Zuzana");

  // Object.Equals checks if variables refer to the same object
Debug.Assert(p1.Equals(p2));
}

Value types, on the other hand are separate individual copies. Two value type variables always point to two different copies of the data. When you assign one variable to another, the data from that first variable is copied into the second variable. Changing properties of one variable will not change those same properties of the other variable — because the two variables point to two separate objects, both of which are living on the Stack.

// Structs are value types
struct
Person
{
  public string Name;
  public Person(string name)
  {
    Name = name;
  }
}

static void Main()
{
  // Create a new Person on the Stack
Person p1 = new Person("Tony");

  // p2 is a separate copy of p1
Person p2 = p1;

  // Change name of p2
  p2.Name = "Zuzana";

  // p1’s name is still Tony
Debug.Assert(p1.Name == "Tony");

  // p1 and p2 point to different objects
Debug.Assert(! p1.Equals(p2));
}

So that’s a little help for your next technical interview. May you pass with flying colors!

About Tony Sneed

Sr. Software Solutions Architect, Hilti Global Application Software
This entry was posted in Technical. Bookmark the permalink.