Unified Type System Boxing and Unboxing

C# has a unified type system that allows value types to be converted to references of type object and object references to be converted into value types. Value types can be converted into references of type object, and vice versa.

Boxing

Expressions of value types can also be converted to values of type object , and back again. When a variable of value type needs to be converted to object type, an object box is allocated to hold the value and the value is copied into the box. This process is known as boxing.

int p = 123;
object box;
box = p; // Boxing (implicit)
box = (object) p; // Boxing (explicit)

The boxing operation can be done implicitly, or explicitly with a cast to an
object. Boxing occurs most typically when a value type is passed to a parameter of type object.

Unboxing

When a value in an object is converted back into a value type, the value is  copied out of the box and into the appropriate storage location. This process is  known as unboxing.

p = (int) box; // Unboxing

You must perform unboxing with an explicit cast operator.
If the value in the reference is not the exact type of the cast, the cast will raise an InvalidCastException.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: