PDA

View Full Version : Boxing and Unboxing in C#


DotNet
18-01-2010, 08:03 PM
Boxing is the term used in programming for converting any datatype to an object. So, an integer, e.g., "12345" can be treated as an object and its properties can be accessed on runtime.

Unboxing is the term used for the conversion of an object into any of the available datatype. So, in case we have an object of a class which has just one data member defined, with a few functions to use it, we can convert the object to the type of the data member.

Boxing in C# - C# has a very good advantage in this regard, over other languages. In C#, everything is an object. So, when we declare an integer, an object of the integer class (classes for the default datatypes are pre-defined in C# under System namespace), is created. That means, there is essentially no such thing as Boxing in C#.

For example, check out this piece of code.

Console.WriteLine (1234.ToString());

This code prints "1234" on the command prompt. No big thing yet. But consider the fact, that we didn't declared any variable. We just wrote a number, which is automatically converted to an object of integer class, and the property of integer class "ToString" is called. The "ToString" function takes a variable as an input and convert it to string. But we didn't passed any variable to it, but an object created by C# runtime without any thing to be done from our part. Here the integer value is converted to an object (which is Boxing, essentially), without programmer's intervention. Cool, huh?



Unboxing in C# - Unboxing in C# is not as straightforward as boxing. We have to determine the datatype that we want the object to be converted to.

Consider this code for better understanding.

int a = 123;
object myobject = num1; //boxing
int num2 = (int) myobject; //unboxing


Here in second line, num1 is converted to an object, just like a normal assignment operator. But to convert the object back to integer and assign it to a new integer variable, we have to write "(int)" before the object variable to define which type of unboxing are we going to use. After the object is converted to integer, it is simply assigned to new variable. Just like C++, isn't it. That's the beauty of C#. If you know C++, you don't need to learn a lot. You are already familiar with most of the concepts, when you learned C++.