When you declare a variable in .Net, it allocates some chunk of memory in RAM. This memory has three things :
data type &
value of the variable.
Depending upon the data type there are two types of memory allocation: Stack and Heap
public void Method1()
// Line 1
// Line 2
class1 cls1 = new class1();
Line1: When Line1 is executed the compiler allocate small chunk of memory in the Stack.
Line2: It allocates memory for y on top of the first memory in Stack (LIFO).
Line3: Here an object is created. When this line is executed it creates a pointer on Stack and the actual object is stored in a Heap memory.
NB: Reference pointer is allocated on Stack. The statement
doesn’t allocate memory for an instance of Class1, it only allocates a stack variable cls1 (and sets it to null). The time it hits new keyword, it allocates on “heap”.
Exiting the above Method
On exiting the method, it clears all the memory variable which are assigned on Stack.
But it didn’t de-allocate the heap memory. This memory will be later de-allocated by the garbage collector.
Now we have discussed about the Stack & Heap memory. Let’s move on to Value & Reference Types.
1. Value types are types which hold both memory & data on the same location i.e Stack.
2. Below we assign an int value (i) to another int value (y). Both these memory are separately allocated on stack. So if we change either of them then other doesn’t change. This is Value type.
1. A reference type has a pointer which points to the memory location.
2. Now when we create an object and assign an object to another object, they both point to same memory location (in heap). So if we change one of them, the other object is also affected. This is Reference type.
When we move data from Value type to Reference type, data is moved from Stack to Heap. It is termed as Boxing.
When we move data from Reference type to Value type, data is moved from Heap to stack. It is termed as Unboxing.