Thursday 14 February 2008

What is Boxing and UnBoxing?

Source: http://aspalliance.com/986_Boxing_and_Unboxing_in_NET.all

Boxing and Unboxing are two important portions of .NET technology. Many of the developers are not really aware of it, but it is really needed if somebody is interested in enhancing the performance of the application developed.

In a very brief way, one can say that Boxing is nothing but converting a value type object to a reference type object. Unboxing is completely explicit. The idea will be clearer after discussing the example given below. This example shows how an integer type is converted to a reference type using the boxing and then unboxed from the object type to the integer type.

class Test
{
static void Main()
{
int i = 1; // i is an integer. It is a value type variable.
object o = i;
// boxing is happening. The integer type is parsed to //object type
int j = (int)o;
// unboxing is happening. The object type is unboxed to //the value type
}
}

In the above example, it is shown how an int value can be converted to an object and back again to an int. This example shows both boxing and unboxing. 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 is just the opposite. 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.

No comments: