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.
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.
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.
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.