Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type. When the CLR boxes a value type, it wraps the value inside a System.Object and stores it on the managed heap. Unboxing extracts the value type from the object. Boxing is implicit; unboxing is explicit. The concept of boxing and unboxing underlies the C# unified view of the type system, in which a value of any type can be treated as an object. In the following example, the integer variable i is boxed and assigned to object o.
int i = 123; // The following line boxes i. object o = i;
The object o can then be unboxed and assigned to integer variable i:
o = 123; i = (int)o; // unboxing
The following examples illustrate how boxing is used in C#.
// String.Concat example. // String.Concat has many versions. Rest the mouse pointer on // Concat in the following statement to verify that the version // that is used here takes three object arguments. Both 42 and // true must be boxed. Console.WriteLine(String.Concat("Answer", 42, true));
// List example. // Create a list of objects to hold a heterogeneous collection // of elements. List
In relation to simple assignments, boxing and unboxing are computationally expensive processes. When a value type is boxed, a new object must be allocated and constructed. To a lesser degree, the cast required for unboxing is also expensive computationally.