Boxing And UnBoxing

Boxing and Unboxing are two important portions of .NET technology. Boxing is nothing but converting a value type object to a reference type object. Unboxing is completely explicit.

Now let us get an idea regarding reference type and value type objects. We all know that a new operator returns the memory address of an object that is allocated from the managed memory (a pool of memory). We usually store this address in a variable for our convenience. These types of variables are known as reference variables. However, the value type variables are not supposed to have the references; they always used to have the object itself and not the reference to it.

Now if we consider the statement written above in Listing 3, the C# compiler will detect System.Int32 as a value type and the object is not allocated from the memory heap, assuming this as an unmanaged one.

In a general way we should declare a type as a value type if the following are true.

1. The type should be a primitive type.
2. The type does not need to be inherited from any other types available.
3. No other types should also be derived from it.

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

No comments: