C# Interview Question #6

What is the difference between stack and heap memory?

C# & .NET Fundamentals Junior Beginner

Quick Interview Answer

The stack is primarily associated with method execution frames, parameters, and local variables. The managed heap is used for dynamically allocated objects.

Detailed Explanation

The stack is primarily associated with method execution frames, parameters, and local variables. The managed heap is used for dynamically allocated objects.

For example, when a class instance is created with new, the object is normally allocated on the managed heap. A local variable may contain the reference to that object.

A common interview simplification says value types are stored on the stack and reference types on the heap, but this is not always technically correct. Storage depends on context. For example, a value-type field inside a class is stored as part of the heap-allocated class object.

Code Example

int age = 30;
Person person = new Person();