C# Memory Management - Part 1

Sena Kılıçarslan
C# Programming
Published in
4 min readMar 5, 2019

In this article, I want to mention how memory management is done in .NET environment. I will try to keep it simple and short so that people with different levels of knowledge and experience can benefit from this. I believe this topic is very important in writing good-quality code and besides, it is popular in programming interviews.

I am planning to write this in three parts in order to make it easy to read. This part will include the topics:

  • Stack and heap
  • Value types and reference types

If you are ready, let’s start :)

Stack and Heap

Stack and heap are portions of the memory. The Common Language Runtime (CLR) allocates memory for objects in these parts.

Stack is a simple LIFO(last-in-first-out) structure. Variables allocated on the stack are stored directly to the memory and access to this memory is very fast, and its allocation is done when the program is compiled. When a method is invoked, the CLR bookmarks the top of the stack. The method then pushes data onto the stack as it executes. When the method completes, the CLR resets the stack to its previous bookmark, popping all the method’s memory allocations is one simple operation.

Heap can be viewed as a random jumble of objects. It allows objects to be allocated or deallocated in a random order. Variables allocated on the heap have their memory allocated at run time and accessing this memory is a bit slower, but the heap size is only limited by the size of virtual memory. The heap requires the overhead of a garbage collector to keep things in order.

Value type variables are stored in the stack and reference type variables are stored in the heap. (This is a very general statement based on the information here.)

Value Type and Reference Type

A value type holds the data within its own memory location.

Value types => bool, byte, char, decimal, double, float, int, long, uint, ulong, ushort, enum, struct

A reference type contains a pointer to another memory location that holds the real data.

Reference types => class, interface, delegate, string, object, dynamic, arrays

If you assign a value type variable to another variable, the value is copied directly.

Here is an example for a value type variable copy:

Output:

As you see in the output, both variables work independently.

If you assign a reference type variable to another, as reference type variables represent the address of the variable, the reference is copied and both variables point to the same location of the heap.

Below is an example of reference variable copy:

Output:

Have you noticed how Alice lost her name :) As these types of copies can result in unexpected behaviours in our programs, we should be careful when we copy reference type variables.

Now we have a general idea about the stack, heap and value/reference type variables. Additionally, I want to provide two very helpful resources which explain in detail how variables are stored in the memory.

First one is Jon Skeet‘s blog post. Below is a citation from his post:

The memory slot for a variable is stored on either the stack or the heap. It depends on the context in which it is declared:

· Each local variable (i.e. one declared in a method) is stored on the stack. That includes reference type variables — the variable itself is on the stack, but remember that the value of a reference type variable is only a reference (or null), not the object itself. Method parameters count as local variables too, but if they are declared with the ref modifier, they don’t get their own slot, but share a slot with the variable used in the calling code.

· Instance variables for a reference type are always on the heap. That’s where the object itself “lives”.

· Instance variables for a value type are stored in the same context as the variable that declares the value type. The memory slot for the instance effectively contains the slots for each field within the instance. That means (given the previous two points) that a struct variable declared within a method will always be on the stack, whereas a struct variable which is an instance field of a class will be on the heap.

· Every static variable is stored on the heap, regardless of whether it’s declared within a reference type or a value type. There is only one slot in total no matter how many instances are created.

Second is Wallace Kelly’s YouTube video. I strongly recommend you watch this video as he demonstrates the topic in a perfect way. After watching that, you will see how everything fall into place in your mind :)

Here I conclude part one of this series. Hope you liked it and found helpful. Please let me know if you have any improvements and/or corrections.

You can find the following posts below:

If you want to find out more about value type and reference type variables, you can check the below posts:

Bye!

References

https://docs.microsoft.com/tr-tr/dotnet/csharp/language-reference/keywords/value-types-table

https://docs.microsoft.com/tr-tr/dotnet/csharp/language-reference/keywords/reference-types

http://net-informations.com/faq/net/stack-heap.htm

http://www.albahari.com/valuevsreftypes.aspx

--

--

Sena Kılıçarslan
C# Programming

A software developer who loves learning new things and sharing these..