Boxing
Implicit conversion of a value type (int, char etc.) to a reference type (object), is known as Boxing. In boxing process, a value type is being allocated on the heap rather than the stack.
Unboxing
Explicit conversion of same reference type (which is being created by boxing process); back to a value type is known as unboxing. In unboxing process, boxed value type is unboxed from the heap and assigned to a value type which is being allocated on the stack.
For Example:
- / int (value type) is created on the Stack
- int stackVar = 12;
- // Boxing = int is created on the Heap (reference type)
- object boxedVar = stackVar;
- // Unboxing = boxed int is unboxed from the heap and assigned to an int stack variable
- int unBoxed = (int)boxedVar;
Another Example:
int x = 10;
string s = string.Format( "The value of x is {0}", x ); // x is boxed here