[ Team LiB ] Previous Section Next Section

5.6 Boxing and Unboxing Types

Boxing 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. It is this process that allows us to call the ToString( ) method on the integer in Example 5-4.

Java programmers take note: In Java, wrapping basic types in objects requires the explicit use of wrapper types like Integer and Float. In C#, the boxing mechanism takes care of all of this for you automatically; wrapper types are unnecessary.

5.6.1 Boxing Is Implicit

Boxing is an implicit conversion of a value type to the type Object. Boxing a value allocates an instance of Object and copies the value into the new object instance, as shown in Figure 5-4.

Figure 5-4. Boxing reference types
figs/pcsharp3_0504.gif

Boxing 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 Explicit

To return the boxed object back to a value type, you must explicitly unbox it. You should accomplish this in two steps:

  1. Make sure the object instance is a boxed value of the given value type.

  2. Copy the value from the instance to the value-type variable.

Figure 5-5 illustrates.

Figure 5-5. Boxing and then unboxing
figs/pcsharp3_0505.gif

For the unboxing to succeed, the object being unboxed must be a reference to an object that was created by boxing a value of the given type. Boxing and unboxing are illustrated in Example 5-5.

Example 5-5. Boxing and unboxing
using System;
public class UnboxingTest 
{
   public static void Main( ) 
   {
      int i = 123;

      //Boxing
      object o = i;

      // unboxing (must be explict)
      int j = (int) o;
      Console.WriteLine("j: {0}", j);
   }
}

Example 5-5 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.

    [ Team LiB ] Previous Section Next Section