Boxing and Unboxing
hi
what is boxing and why it is used
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Kirtan PatelPosted Dec 1, 2009, 7:31 AM
Here is Explanation.
Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type. When the CLR boxes a value type, it wraps the value inside a System.Object and stores it on the managed heap. Unboxing extracts the value type from the object. In the following example, the integer variable i is boxed and assigned to object o.
theLizardPosted Dec 3, 2009, 2:27 AM
Purushottam RathorePosted Dec 1, 2009, 7:19 AM
Boxing example:
using System;
class ConversionSamp
{
static void Main()
{
int a = 5;
Object obj = a;
Console.WriteLine(a.ToString());
Console.WriteLine(obj.ToString());
}
}
Unboxing: The process of converting from a reference type to a value type is called unboxing.
Unboxing example:
using System;
class ConversionSamp
{
static void Main()
{
Object obj = 5;
int a = (int)obj;
Console.WriteLine(a.ToString());
Console.WriteLine(obj.ToString());
}
}
Lalit MPosted Dec 1, 2009, 2:07 AM
In the following C# example, the variable PI is a double and this is allocated on the stack. However, when it is passed to the function foo, it must be "boxed" which involves making a copy of it on the heap. There is overhead in this. Within foo, even though o references the value 3.14159, it must be cast back (unboxed) to a double to be used. Again, there is overhead in this.
static void foo(object o){
double x = (double) o; // unboxing
Console.WriteLine( x );
}
static void main()
{
double PI = 3.14159;
foo( PI ); // PI is boxed when passed to o
}
Boxing and Unboxing with examples
more example
---------------
Boxing is converting a value type to reference type
Unboxing is an explicit operation.
Eg.
In C# :
int X 1;
Object Y;
int Z;
Y X; -------------> This is BOXING
Z (int)Y; ----------------> This is UNBOXING