Sunday, March 1, 2009

Boxing Unboxing in C#

All types in c# are derived from the System.Object base class. In .NET languages, there are basically two types:

1. Value type (derived from System.ValueType) - The struct and primitive types are stored on the stack (very fast accessible memory area)
2. Reference type (derived from System.Object) - the object types are stored on the heap (in case of .NET its managed 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.

class Test
{
static void Main()
{
int i = 1;
object o = i; // boxing

int j = (int) o; // unboxing

}
}

BOXING:

Converting a value type to reference type is called Boxing. When a variable of a value type needs to be converted to a reference type, an object box is allocated to hold the value, and the value is copied into the box.

UNBOXING:

Converting a reference type back to it's value type is called un-boxing. When an object box is cast back to its original value type, the value is copied out of the box and into the appropriate storage location.

You cannot Implicitly convert a reference type to a value type. Unboxing is an explicit operation. E.g., if a variable x is boxed as Int32 variable, then it must be unboxed to Int32 variable. So, the type the variable uses to box will remain the same when unboxing the same variable.

Note: In relation to simple assignments, boxing and unboxing are computationally expensive processes. When a value type is boxed, an entirely new object must be allocated and constructed. To a lesser degree, the cast required for unboxing is also expensive computationally.

Actually when a value type is boxed, an entirely new object must be created. This can take up to 20 times longer than an assignment. When unboxing, the casting process can take four times as long as an assignment.

0 comments: