Understanding Boxing and Unboxing in C#

Boxing is the process of converting a value type to the type object. Unboxing extracts the value type from the object. Let’s see how boxing and unboxing works.



Boxing: This is an implicit process. That means developer doesn’t need do any type casting.
See below line of code:
int boxingInteger = 123;

This will create a block on stack memory area for variable of type int.

Stack

boxingInteger


Now see below line of code:
object myObject = boxingInteger; // boxing

This is the step where boxing is occurring. When above line is executed, two things will occur at backend.
1.       An object will be created on heap area that will hold value of boxingInteger.
2.       Reference type myObject will get created that will point to memory area allocate in above step.
Note: It will not affect boxingInteger variable on stack. The entry on stack will be there after boxing.



Unboxing: It is reversing of boxing. But it is explicit. Developer need to do type casting explicitly. It will type case object on heap to the value type.
From above example,
int unboxingInteger = (int)myObject;  // unboxing

It will convert value at my object from object type to type int and it will assign this value to variable unboxingInteger which will get created on stack area.

Stack

unboxingInteger
boxingInteger



Myth about Boxing:
Myth: Below code does boxing.
string sMyString = “Box”;
object myObject =   sMyString

Truth: string is not a value type variable. It is a reference type variable. So when you are assigning sMyString to myObject, you are just copying reference. There is no value type to object type conversion is happening here.


To get depth knowledge check this:
http://www.codeguru.com/Csharp/Csharp/cs_syntax/article.php/c5883

2 comments:

Sudhir DBAKings said...

Nice post very helpful

dbakings

Sagar Wagh said...

Hi Sudhir, Thank you for your valuable feedback! :)

Post a Comment