#185 – The Heap and the Stack

In C#, all objects are created on either the heap or the stack.

The stack is an area of memory where the following is stored:

  • Objects whose type is a value type
    • (e.g. enums, built-in types and structs)
  • Values of parameters passed to methods
  • References to objects created on the heap   (aka pointers)

The heap is an area of memory where the following is stored:

  • Objects that are instances of reference types
    • (e.g. strings, arrays, built-in types in the .NET framework, custom types)

Memory for objects created on the stack is allocated when a method is called or when the object is instantiated.  The memory is released when the method that instantiated the object exits.

Memory for objects created on the heap is allocated when the object is instantiated and managed by the CLR garbage collector, which frees memory periodically.

Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

5 Responses to #185 – The Heap and the Stack

  1. Pingback: #187 – Everything Is an Object « 2,000 Things You Should Know About C#

  2. Pingback: #188 – Objects Are on the Heap, References to Objects Are on the Stack « 2,000 Things You Should Know About C#

  3. Pingback: #227 – Instances of Classes Are Created on the Heap « 2,000 Things You Should Know About C#

  4. Pingback: #925 – The Managed Heap | 2,000 Things You Should Know About C#

  5. kai zhou says:

    Nice summary, thank you Sean.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: