xxxxxxxxxx
/*
Boxing: The process of converting a value type instance to an object refrence.
When boxing happens CLR creates an object in the Heap and then creates a
a reference in the stack. So the value stroed in the heap along with an
object refernce in the stack when boxing.
*/
//boxing:
int a = 10;
object obj = a;
// or
object obj = 10;
/*
Unboxing: Is the opposition of boxing; Now when we cast an object to an integer
unboxing happens and the result is we get a new variable on the stack called
number with value of 10.
*/
object obj = 10;
int number = (int) ob;
/*
Both boxing and unboxing have a performance penalty because of that extra
object creation. And that's someting you should avoid if possible.
It's better to use a generic implemention of that class if it exists.
*/
xxxxxxxxxx
Boxing is the process of converting a value type (such as an int or double)
to a reference type (such as an object). This is done by allocating memory
on the managed heap to hold the value, and then storing the address of that
memory location in the reference type.
//example
int i = 123;
// Box the int value and store it in an object
object o = i;
Unboxing is the process of converting a reference type back to a value type.
This is done by retrieving the value stored in the reference type and copying
it to a value type variable.
//example
object o = 123;
// Unbox the object and store it in an int
int i = (int)o;
xxxxxxxxxx
class BoxingUnboxing
{
static void Main()
{
int myVal = 1;
object obj = myVal; // Boxing
int newVal = (int)obj; // Unboxing
}
}