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.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Kirtan PatelRank #292 · 8.6K reputationPosted Dec 1, 2009, 2:31 AM EST
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.
int i = 123; object o = (object)i; // boxing o = 123; i = (int)o; // unboxingLalit MRank #1,186 · 1.5K reputationPosted Nov 30, 2009, 9:07 PM EST
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
Purushottam RathoreRank #120 · 18.2K reputationPosted Dec 1, 2009, 2:19 AM EST
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());
}
}
theLizardRank #1,079 · 1.8K reputationPosted Dec 2, 2009, 9:27 PM EST