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 reference type (object) to a value type is known as UNBOXING.
In unboxing process, boxed value type is unboxed ffrom the heap and assigned to a value type which is being alloccated on the stack.
example: int stackvar = 15;
Object boxedvar = stackvar; //Boxing = int is created on the heap (reference type)
int Unboxed = (int) boxedvar; // Unboxing = boxed int is unboxed from the heap
// and assigned to an int stack variable.
example: int i = 5;
Arraylist arr = new Arraylist();
// Arraylist contains object type value.
arr.Add(i);n //Boxing occurs automatically.
int j = (int) arr[0]; //Unboxing occurs.
Issues with boxing and unboxing:
- Sometime boxing is necessary, but avoid it if possible, since it slow down the performance and increase memory requirements.
- Attempting to unbox a null causes a NullreferenceException.
example: int? stackvar = null;
object boxedvar = stackvar;
//NullReferenceException
int unboxed = (int) boxedvar;
// Object reference not set to an instance of an object.
- Attempting to unbox a reference to an incompatible value type causes an InvalidCastException.
example: int stackvar = 15;
object boxedvar = stackvar;
// InvalidCastException
float unboxed = (float) boxedvar; // Specified cast is not valid;