Tuesday, 2 July 2013

Understanding Stack and Value type

Welcome buddies,

In my previous post I have explained C# - Dot net datatypes. Now I am going to explain what is Stack, Heap memory? and what is Value type and Reference type? Let's start,

Basically here I mean Stack is memory. Value types is data which are stored in this memory. Consider the below diagram,


In the above code I declare two integer variable i,y and assign value 1 to i. Also reassign the i to y. In  C# - Dot net datatypes I mentioned integer datatype will get 32 bytes memory to represent the value. So when first code executed, a chunk of memory allocated which size would be 32 bytes. 

In the second line we just reassigned the i value to y, So the expected memory allocation should be like below,
But the actual allocation be like below image,
That means It allocates new chunk of memory for the y. So we conclude definition "When the values reassign instead of reuse the previously allocated memory, if new chunk of memory is created then the data is called Value type". In other words "All C# - Dot net datatypes are Value types and memory allocated for value types is called Stack memory". When the program execution has finished all allocated space in Stack memory deallocated automatically. 

In my next post I have explained What is Heap and Reference type?

0 comments:

Post a Comment