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 you to call the ToString( ) method on the integer in Example 6-4.
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 6-4.
Boxing is implicit when you provide a value type where a reference is expected. The compiler notices that you've provided a value type and silently boxes it within an object. You can, of course, explicitly cast the value type to a reference type, as in the following:
Dim myIntegerValue As Integer = 5 Dim myObject As Object = myIntegerValue ' explicitly cast to object myObject.ToString( )
This is not necessary, however, as the compiler will box the value for you, silently and with no action on your part:
Dim myIntegerValue As Integer = 5 myIntegerValue.ToString( ) ' boxed for you
To return the boxed object back to a value type, you must explicitly unbox it if Option Strict is On (as it should be). You will typically unbox by using the DirectCast( ) function or the CType( ) function. Figure 6-5 illustrates unboxing.
Boxing and unboxing are illustrated in Example 6-5.
Option Strict On Imports System Public Class UnboxingTest Public Shared Sub Main( ) Dim myIntegerVariable As Integer = 123 ' boxing Dim myObjectVariable As Object = myIntegerVariable Console.WriteLine("myObjectVariable: {0}", _ myObjectVariable.ToString( )) ' unboxing (must be explicit) Dim anotherIntegerVariable As Integer = _ DirectCast(myObjectVariable, Integer) Console.WriteLine("anotherIntegerVariable: {0}", _ anotherIntegerVariable) End Sub End Class Output: myObjectVariable: 123 anotherIntegerVariable: 123
Example 6-5 creates an integer myIntegerVariable and implicitly boxes it when it is assigned to the object myObjectVariable; then, to exercise the newly boxed object, its value is displayed by calling ToString( ).
The object is then explicitly unboxed and assigned to a new integer variable, anotherIntegerVariable, whose value is displayed to show that the value has been preserved.
Typically, you will wrap an unbox operation in a try block, as explained in Chapter 11. If the object being unboxed is null or is a reference to an object of a different type, an InvalidCastException error occurs.
As an alternative, you can use the TypeOf( ) function, as follows:
' unboxing (must be explicit) If TypeOf (myObjectVariable) Is Integer Then Dim anotherIntegerVariable As Integer = _ DirectCast(myObjectVariable, Integer) Console.WriteLine("anotherIntegerVariable: {0}", _ anotherIntegerVariable) End If
Top |