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 allowed us to call the ToString( ) method on the integer in Example 5-4.

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.

Boxing reference types

Figure 5-4. Boxing reference types

Boxing is implicit when you provide a value type where a reference is expected and the value is implicitly boxed. 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 illustrated 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.

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 unboxing.

Boxing and then unboxing?

Figure 5-5. Boxing and then unboxing?

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.9.147