Today’s topic is in complete contrast to the one I talked about yesterday. Unboxing literally means taking something out of the box. You must have done this quite often! Like unwrapping a gift, opening up a package which you placed an order for.
This is exactly how it works in programming languages. As I had explained earlier, Boxing means converting a value type to a reference type and placing it in the heap portion of the memory.
UnBoxing is just the opposite. Here, The reference type is converted to a value type and it is placed in the stack portion of the memory. The element is unwrapped from the object and it is converted to a value type.
Let’s take an example
Suppose we have a reference type like this-
In order to convert to a value type we have to use the casting operator, something which I would explain in my forthcoming blogs.
So, this basically means we are trying to cast the object to an integer by using the casting operator (int).
So, now you could write-
Console.WriteLine(” “+i); In C#
System.println(” “+i); In Java
Cout<<” “<<i; In C++
All the statements which I listed above do the same thing. They print a value. The only thing is that the syntax is different. Once you try executing any of the statements in the respective languages. The output would be the same, which is 56. And it shows that we have successfully unboxed the element from the heap.