5.6. Boxing and Unboxing TypesBoxing and unboxing are the processes that enable value types (e.g., integers) to be treated as reference types (objects). The value is "boxed" inside an Object, and subsequently "unboxed" back to a value type.
5.6.1. Boxing Is ImplicitBoxing is an implicit conversion of a value type to the type Object. Boxing a value allocates an instance of the boxed type and copies the value into the new object instance, as shown in Figure 5-4. Figure 5-4. Boxing reference typesBoxing is implicit when you provide a value type where a reference is expected. For example, if you assign a primitive type, such as an integer to a variable of type Object (which is legal because int derives from Object), the value is boxed, as shown here: using System; class Boxing { public static void Main( ) { int i = 123; Console.WriteLine("The object value = {0}", i); } } Console.WriteLine( ) expects an object, not an integer. To accommodate the method, the integer type is automatically boxed by the CLR, and ToString( ) is called on the resulting object. This feature allows you to create methods that take an object as a parameter; no matter what is passed in (reference or value type), the method will work. 5.6.2. Unboxing Must Be ExplicitTo return the boxed object back to a value type, you must explicitly unbox it. You should accomplish this in two steps:
Figure 5-5 illustrates. Figure 5-5. Boxing and then unboxingFor the unboxing to succeed, the object being unboxed must be of the appropriate type for the variable you are assigning it to. Boxing and unboxing are illustrated in Example 5-4. Example 5-4. Boxing and unboxing#region Using directives using System; using System.Collections.Generic; using System.Text; #endregion namespace boxing { public class UnboxingTest { public static void Main( ) { int i = 123; //Boxing object o = i; // unboxing (must be explicit) int j = ( int ) o; Console.WriteLine( "j: {0}", j ); } } } Example 5-4 creates an integer i and implicitly boxes it when it is assigned to the object o. The value is then explicitly unboxed and assigned to a new int whose value is displayed. Typically, you will wrap an unbox operation in a try block, as explained in Chapter 11. If the object being unboxed is null or a reference to an object of a different type, an InvalidCastException is thrown. |