Boxing is required when a value
type must be assigned to a variable as a reference type. To accomplish this type of conversion,
simply declare an object and set its value to that of the value type variable. When you do this, an
object is allocated dynamically on the heap that contains the value of the value type. Chapter 3
covers boxing in VB extensively. The following code demonstrates boxing:
Public Class EntryPoint
Shared Sub Main()
Dim EmployeeID As Integer = 303
Dim BoxedID As Object = EmployeeID
Dim UnboxedID As Integer = CInt(BoxedID)
CHAPTER 2 n VB 2008 SYNTAX 22
EmployeeID = 404
System.Console.WriteLine(EmployeeID.ToString())
System.Console.WriteLine(UnboxedID.ToString())
End Sub
End Class
Running the preceding code will display the following in the console window:
404
303
Boxing occurs when the Object variable BoxedID is assigned the Integer variable EmployeeID.
A heap-based object is created, and the value of EmployeeID is copied into it. This is how the gap is
bridged between the value type and the reference type worlds within the CLR. The BoxedID object
actually contains a copy of the EmployeeID value. This point is demonstrated in the snippet when
the original EmployeeID value is printed after the boxing operation.
Pages:
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73