What is Boxing and UnBoxing?

Boxing is implicit conversion of ValueTypes to Reference Types (Object). 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. Boxing is conversion from value type to object(reference) type. Actually the copy of value type copied from stack to heap memory.
Boxing Conversion

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

Unboxing Conversion
UnBoxing is explicit conversion of Reference Types (Object) to its equivalent ValueTypes. It requires type-casting. Unboxing extracts the value type from the object. In this example, the integer variable i is boxed and assigned to object o. Unboxing is reverse of it.from heap memory back to stack memory.

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

Tagged , . Bookmark the permalink.

Leave a Reply