What is boxing and unboxing in C#? Difference and example.
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 .
1 2 3 4 5 6 | //boxing int score = 12; object obj = score; //unboxing int unbox = (int)obj; |
BOXING | UNBOXING |
---|---|
Converts value type to object. | Converts an object to value type. |
Implicit conversion. object obj = 123; | Explicit conversion. Casting required int i = (int)obj; |
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.
1 2 3 4 | var objlist = new ArrayList(); objlist.Add(1); objlist.Add('c'); objlist.Add(true); |
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.
1 2 3 4 | int numIndex0 = (int)objlist[0]; // returns 1 char charIndex1 = (char)objlist[1]; // returns c bool boolIndex2 = (bool)objlist[2]; // returns true char boolIndex2 = (char)objlist[2]; // InvalidCastException |