Tuesday, 2 July 2013

Understanding Heap and Reference type

Hello all,

In continuation to my previous post Understanding Stack and Value type, Now I am going to explain what is Heap memory? and what is Reference type? Let's start,

Basically here I mean Heap is memory. Reference type is data which are stored in this memory. Consider the below diagram,



Understanding Heap and Reference type


In the above code I declare two variables as data type object. As Microsoft definition "The object type is an alias for System.Object in the .NET Framework. You can assign values of any type to variables of type object." When the first line of code (object i=1;) executed, like value type here too the space allocated in Stack memory. But Stack memory having reference address only. Originally data stored in heap memory. For better understanding see image below,
Understanding Heap and Reference type


In the second line we just reassigned the i value to y, So the memory allocation should be like below,

Understanding Heap and Reference type

So above picture clearly shows, Reference types data would not reallocate the memory for reassign. 

Points to remember

  • Other than Dot net data types such as Object, user defined data types (Class) are called Reference types. 
  • Memory used to store the Reference types data is called Heap Memory. 
  • When the Program execution has stopped, Stack memory has cleared automatically. But Heap memory will not be cleared automatically. 
  • Heap memory is cleaned by Garbage Collector.
  • Generally value types are faster than Reference types, because in reference types boxing will occur

0 comments:

Post a Comment