.NET 1.1+Boxing and Unboxing
When you wish to use a value type with a collection or another place where an object is expected, the value type is boxed within the resultant object. To retrieve the value and convert it back into a simple value type, it is unboxed.
Boxing and Unboxing
Boxing and unboxing are processes that permit value types to be held within, and treated as, objects. When a variable of the type System.Object is assigned a value that is a value type, the value is "boxed" within the object. This allows it to be used as an object within properties, parameters, etc.
Boxing is particularly useful when working with the basic collection classes. As these collections may only hold objects, any value types added to the list of items are automatically boxed inside an object.
To retrieve a boxed value from an object and convert it back into a value type, you must "unbox" it. This is achieved by simply casting the object to the appropriate value type. In the sample code below, the integer variable is boxed within a new object. The second integer variable retrieves the value from the object.
int original = 10;
object boxed = original;
int unboxed = (int)boxed;
6 September 2008