Showing posts with label Why we need boxing and unboxing. Show all posts
Showing posts with label Why we need boxing and unboxing. Show all posts

Saturday 19 September 2015

Boxing And Unboxing in DotNet

Boxing and unboxing

I Recommend to Go to this link to Read about Value Types and Reference Types Before Going To Understand the concept of Boxing and Unboxing

Value Types Vs Reference Types Dotnet
http://geeksprogrammings.blogspot.in/2015/09/value-types-vs-reference-types-dotnet.html

Boxing and unboxing are the most important concepts you always get asked in your interviews. Actually, it's really easy to understand, and simply refers to the allocation of a value type (e.g. int, char, etc.) on the heap rather than the stack.

Boxing

Implicit conversion of a value type (int, char etc.) to a reference type (object), is known as Boxing. In boxing process, a value type is being allocated on the heap rather than the stack.

Unboxing

Explicit conversion of same reference type (which is being created by boxing process); back to a value type is known as unboxing. In unboxing process, boxed value type is unboxed from the heap and assigned to a value type which is being allocated on the stack.

For Example
    // int (value type) is created on the Stack
    int stackVar = 12;
    
    // Boxing = int is created on the Heap (reference type)
    object boxedVar = stackVar;
    
    // Unboxing = boxed int is unboxed from the heap and assigned to an int stack variable
    int unBoxed = (int)boxedVar;


Real Life Example

    int Val_Var = 10;
    ArrayList arrlist = new ArrayList();
    
    //ArrayList contains object type value
    //So, int i is being created on heap
    arrlist.Add(Val_Var); // Boxing occurs automatically Because we are Converting int to Object Type This is Called Boxing
    
    int j = (int)arrlist[0]; // Unboxing occurs

Performance implication of boxing and unboxing

In order to see how the performance is impacted, we ran the below two functions 10,000 times. One function has boxing and the other function is simple. We used a stop watch object to monitor the time taken.
The boxing function was executed in 3542 ms while without boxing, the code was executed in 2477 ms. In other words try to avoid boxing and unboxing. In a project where you need boxing and unboxing, use it when it’s absolutely necessary.

Boxing And Unboxing in DotNet
Boxing And Unboxing in DotNet