Boxing and Unboxing

1:25 AM

Boxing Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type.  Refer MSDN

Boxing will take Variable from Stack (Value types) and store it into Heap (Object type)

Boxing is implicit. There is no need to type cast the value type to Object Type.

Example:



String mystr = "Welcome to C# boxing";

Object myObj = mystr;  // Implicit conversion of String to Object




Unboxing:  It's the reverse of boxing. It needs to be done explicitly by user.

Example:



String mystr = "Welcome to C# boxing";

Object myObj = mystr;  // Implicit conversion of String to Object

String mystr2 = (String) myObj; // Explicit conversion from Object to String