How Boxing And Unboxing Works With Stack And Heap In C#

Introduction

 
In last article on TypeCasting we figured out what different kind of data types there are  in C# & how we can convert one into another.
 

What do we know so far?

  • We know there are 2 kinds of data types

    • Value Type
    • Object Type

What do we need to know?

  • We must understand what is Heap & Stack: When we create an instance of a reference type or declare a value type these both of them stored into RAM. But the form at which these memories are allocated is quite different.
  • The stack is used for static memory allocation; i.e. its allocation is done when the program is compiled, whereas the heap is used for dynamic memory allocation; i.e. objects are allocated at run time

    Let's see an example,
    1. class Program {  
    2.     static void Main(string[] args) {  
    3.         int age = 25;  
    4.         float distance = 4.5 f;  
    5.         IPerson PersonIObj = new Person();  
    6.         Person PersonObj = new Person();  
    7.         Planet PlanetObj = new Planet();  
    8.         Phone PhoneObj = new Phone();  
    9.     }  
    10. }  
    11. public class Person: IPerson {}  
    12. public class Planet {}  
    13. public class Phone {}  
    14. interface IPerson {}  
  • Now let's check what is going on in RAM,
  • What I am trying to show with the diagram is, the value type variables are stored in a stack whereas object reference type is stored in a heap.
  • One more thing which is pretty obvious is stack is a linear data structure (contiguous) whereas heap is Hierarchical data structure. So memory is allocated in a contiguous manner in stack & randomly allocated in heap.
  • Multi-threaded applications have a separate stack for each newly created thread but the heap's scope is an entire application, meaning that all threads in an application share a single heap memory.
So now we also know what is heap & stack, great. Now let's see how these are going to help us understand boxing & unboxing in C#.
  • As per the definition, Boxing is a process of converting value type to a reference type; i.e. wrapping the value inside a reference variable & unboxing is converting reference type back into value type. i.e unwraps the value from reference variable.

Boxing

 
Boxing is an implicit type conversion, as we have learnt that in type casting. But why is it implicit? Because no one is great than the greatest object type. It's like a biggest container in programming, so you can easily convert any other type into it easily.
  • Remember the whole value type is always stored in a stack & referenced type is stored in a heap concept? Let's see what happens in RAM when we do implicit conversion.
    1. int age = 25;  
    2. object objReferenceType = age;  
    3. objReferenceType = age;  



  • Step 1: declare n value type variable age, stored into a stack
  • Step 2: declare an object type reference variable, stored into a heap
  • Step 3: convertion of value type into reference type, which copies the value of age & stores into a reference type.

Unboxing

 
Unboxing is an explicit type conversion, as we have learned in type casting. You must have figured out by now why it's explicit? Yes, because as object type is the biggest container in programming, you need to explicitly fit bigger container (an object) into smaller containers (any other value type).
  1. int age = 25;    
  2. object objReferenceType = new object();    
  3. age = (int)objReferenceType ;   
 
  • Step 1: Declare a value type variable age, stored into stack
  • Step 2: Declare an object type reference variable, stored into a heap
  • Step 3: Conversion of reference type to value type by typecasting, which copies the reference of an object & stores into a value type.

Conclusion

  • Now we know what Boxing & Unboxing is & how to use it in C#
  • We know how it's arranged with respect to heap & stack
  • Tradeoff: Even though it is useful, boxing & unboxing does cost some performance. For boxing, you will have to create a new object & for unboxing, the compiler has to perform extra computational steps.
 There you go. Now you know what boxing & unboxing are and how they are allocated in stack & heap.
 
 Thank you all. I hope  this article was helpful enough for you to implement these new concepts in your application. I wish you all the best.
 
 Happy coding.


Similar Articles