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

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

UnBoxing

Tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>