Boxing and UnBoxing



Boxing and unboxing enable value types to be treated as objects. Boxing a value type packages it inside an instance of the Object reference type. This allows the value type to be stored on the garbage collected heap. Unboxing extracts the value type from the object. In this example, the integer variable i is boxed and assigned to object o.

int i = 123;
object o = (object)i;  // boxing

The object o can then be unboxed and assigned to integer variable i

o = 123;
i = (int)o;  // unboxing



In relation to simple assignments, boxing and unboxing are computationally expensive processes. When a value type is boxed, an entirely new object must be allocated and constructed.This can take up to 20 times longer than an assignment.  To a lesser degree, the cast required for unboxing is also expensive computationally. When unboxing, the casting process can take 4 times as long as an assignment. For more information, see Performance.




Bookmark and Share