Boxing: Converting value type (int, float,char) to reference type (System.Object). In C# any type can be treated as an object.
Unboxing : extracts the value type from the object .
int score = 12;
object obj = score;
int unbox = (int)obj;
|Converts value type to object.||Converts an object to value type.|
|Implicit conversion. ||Explicit conversion. Casting required |
|objects are stored on heap.||value type are stored on stack|
|Boxing is safe.||InvalidCastException on incorrect casting. |
NullReferenceException if value is null.
Drawback: Boxing and unboxing both are expensive operation hence should be used only if necessary.
Example: ArrayList is a built-in data structure in C# which stores elements as an object.
var objlist = new ArrayList();
In the above example each item in the ArrayList is stored as an object hence boxing is performed. To extract values back from the object unboxing needs to be done.
int numIndex0 = (int)objlist; // returns 1
char charIndex1 = (char)objlist; // returns c
bool boolIndex2 = (bool)objlist; // returns true
char boolIndex2 = (char)objlist; // InvalidCastException