by Edward
25 September 2010 17:21
Boxing and unboxing is an important concept in C#’s type system. With Boxing and unboxing you can link between value types and reference types by allowing any value of a value type to be converted to and from type object. When you 'box' a value type, it wraps the value inside a System.Object and stores it on the managed heap. Unboxing does the reverese, it extracts the value type from the object.
The following code snippet demonstrates boxing and unboxing:
public static void Main() {
Int32 v = 5; // Create an unboxed value type variable
Object o = v; // o refers to a boxed version of v
v = 10; // Changes the unboxed value to 10
Console.WriteLine(v + ", " + (Int32) o); // Displays "10, 5"
}
Here is a more simple example:
Boxing:
int i = 5;
object o = i; // boxing
Unboxing:
o = 5;
i = (int)o; // unboxing