Focus on Microsoft Technologies - Tutorials, Articles, Code Samples.

Monday, September 11, 2006

Boxing and Unboxing in .NET

This article deals with the boxing and unboxing in Microsoft .NET.  It is a fact that in our daily coding standards we usually forget to keep track of these things, but each developer should know what it means and that the proper use of this will definitely lead to a powerful application.

Before going into Boxing and Unboxing, it is really very important to understand what a primitive data type is.  All the supported datatypes by the compiler of a language are known as primitive data types.  These data types map directly to the library of the corresponding language.  For example, in C# we are declaring an integer variable as

Listing 1

int a = new int (5);

Or in a friendlier format:

Listing 2

int a = 5

Both listing 1 and 2 are same.

The int data type is a primitive data type of C# and for that reason it maps directly to System.Int32 type.  So the above two lines can be re-written as:

Listing 3

System.Int32 a = new System.Int32 (5) System.Int32 a = 5
Reference and Value types
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.

A few other criteria are also there for this, but are beyond the scope of this article.

Boxing and Unboxing in .NET

Post a Comment