【Boxing & unboxing]
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 # uniied view of the type system in which a value of any type can be treated as an object.
int i = 123;// The following line boxes i.object o = i; o = 123;i = (int)o; // unboxing
View code
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. for more information, see performance.
Unboxing can only correspond to the same type; otherwise, an error occurs, as shown in the following example:
class TestUnboxing{ static void Main() { int i = 123; object o = i; // implicit boxing try { int j = (short)o; // attempt to unbox System.Console.WriteLine("Unboxing OK."); } catch (System.InvalidCastException e) { System.Console.WriteLine("{0} Error: Incorrect unboxing.", e.Message); } }}
View code
Reference: http://msdn.microsoft.com/zh-cn/library/yz2be5wk.aspx