Friday, July 23, 2010

Boxing and Unboxing in C#

C# provides us with Value types and Reference Types. Value Types are stored on the stack and Reference types are stored on the heap. The conversion of value type to reference type is known as boxing and converting reference type back to the value type is known as unboxing.

Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type. When the CLR boxes a value type, it wraps the value inside a System.Object and stores it on the managed heap. Unboxing extracts the value type from the object. In the following example, the integer variable i is boxed and assigned to object o.


int i = 123;
object o = (object)i

The object o can then be unboxed and assigned to integer variable i:

o = 123;
i = (int)o;


Boxing is an implicit conversion of a value type to the type object or to any interface type implemented by this value type. Boxing a value type allocates an object instance on the heap and copies the value into the new object.

Consider the following declaration of a value-type variable:

int i = 123;

The following statement implicitly applies the boxing operation on the variable i:

object o = i;

The result of this statement is creating an object reference o, on the stack, that references a value of the type int, on the heap. This value is a copy of the value-type value assigned to the variable i. The difference between the two variables, i and o, is illustrated in the following figure.

Boxing Conversion





In the above case, I have made an implicit boxing. At first time the i value is located in stack area as actual value. But when the i value is boxed, to object type. So, the reference will be resides on the stack memory area and the value pointing to that reference will be located on heap area.
Example:

class TestBoxing
{
static void Main()
{
int i = 797;
object o = i; // Implicit boxing

i = 456; // Change the contents of i

System.Console.WriteLine("The value-type value = {0}", i);
System.Console.WriteLine("The object-type value = {0}", o);
}
}







The following example demonstrates a case of invalid unboxing and the resulting InvalidCastException. Using try and catch, an error message is displayed when the error occurs.

class TestUnboxing
{
static void Main()
{
int i = 797;
object o = i; // implicit boxing

try
{
int j = (short)o; // attempt to unbox

System.Console.WriteLine("Unboxing Possible.");
}
catch (System.InvalidCastException e)
{
System.Console.WriteLine("{0} Error: Incorrect unboxing.", e.Message);
}
}
}


This program outputs:
Specified cast is not valid. Error: Incorrect unboxing.
If you change the statement:
int j = (short) o;

to:

int j = (int) o;
the conversion will be performed, and you will get the output:
Unboxing Possible.

Unboxing is an explicit conversion from the type object to a value type or from an interface type to a value type that implements the interface. An unboxing operation consists of:
• Checking the object instance to make sure that it is a boxed value of the given value type.
• Copying the value from the instance into the value-type variable.
The following statements demonstrate both boxing and unboxing operations:
int i = 123; // a value type
object o = i; // boxing
int j = (int)o; // unboxing


Unboxing Conversion




In the above figure, i value 123 is stored in the stack, and when it is assigned to object type, the reference will be stored in stack only, but the actual value will be stored in heap. And when, it will be explicitly telecasted to int type, as per the above figure , j value will be stored in the stack.
Difference between Stack vs Heap memory
Stack
Stack memory stores variable types in address' in memory, these variables in programming are called local variables and are often stored for short amounts of time while a function/method block uses them to compute a task.
Once a function/method has completed its cycle the reference to the variable in the stack is removed.

Heap
Heap memory stores all instances or attributes, constructors and methods of a class/object.
Comparison
A Heap reference is stored in Stack memory until the life cycle of the object has completed. Inside the Heap reference all the contents of the object are stored whereas with a local variable only the variable contents are stored in the stack.
Example:
Stack
int x
ref 0x456783 (Heap reference)
int y
ref 0x498702 (Heap reference)
int z


Heap (0x456783)
name => Ali
age => 33
city => CTC
height => 5'8
sex => Male

Heap (0x498702)
name => Saroj
age => 29
city => BBSR
height => 6'0
sex => male

So, above all, I would like to say, for performance point of view, heap is works better then stack.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

No comments:

Post a Comment