Stack, Heap, Value Type, And Reference Type In C#

Introduction

In this article, we will be discussing about Stack, Heap, Value type, and Reference type.

Now, let’s see what happens when we declare any variable like int a=10 in C#. When C# compiler will run, it will allocate a block of memory which will have the name of a variable - a; its type - int; and its value - 10. Now, this memory can be of type Stack or Heap i.e. variable gets stored in Stack or Heap.

Let’s understand with the help of below example.

C#

Now, in the above example, line one is executed then it is stored in Stack. The same process goes for line 2, however, when 3rd line is executed, its reference will be stored on the stack, i.e., class1 obj and its values will be stored on the heap. Once the execution of Method1() gets completed, all memory from stack gets cleared, however, values present in heap will remain there, i.e., obj of class1.

Now, the values present in heap may be cleared by Garbage collector.

However, we can say normal variables like int, Boolean, double float are stored on stack and objects are stored on Heap.

Let's try to understand Value type and reference type.

C#

Now as per the above example, both variables, a and b will have their own chunk of memory allocated and changing the value of b will not affect the value of a and vice-versa.

Now, we can say Value type of variables gets memory allocated separately and modification in the value of any variable will not affect another one.

Let's understand Reference type.

C#

In the above example, we have created instance of class1 as obj and assigned value 10 to I of obj.

After this, we are assigning obj to another instance of class1 i.e. obj1.  And after this we are changing the value of obj1.i to 20. If you will run this program and try to debug the value of obj.i will automatically get updated to 20. So objects are reference type.

Reference type always targets to the same memory location. If you will modify values of any instance, then it will affect another one.

Please refer the below details of value type and reference type variables.

C#


Recommended Free Ebook
Similar Articles