24.2. Primitive-Type Structures; Boxing and UnboxingThe data structures we discuss in this chapter store Object references. As you'll soon see, these data structures can store both primitive- and reference-type values. This section discusses the mechanisms that enable primitive-type values to be manipulated as objects. Primitive-Type StructuresEach primitive type (Appendix L, Primitive Types) has a corresponding Structure in namespace System that declares the primitive type. These Structures are called Boolean Byte SByte Char Decimal Double Single Int16 UInt16 Int32 UInt32 Int64 and UInt64. Types declared with keyword Structure are implicitly value types. Primitive types are actually aliases for their corresponding Structures, so a variable of a primitive type can be declared using the primitive type's keyword or the Structure namee.g., Integer and Int32 are interchangeable. The methods related to a primitive type are located in the corresponding Structure (e.g., method Parse, which converts a String to an Integer value, is located in Structure Int32). Refer to the online documentation for each Structure type to see the methods for manipulating values of that type. Boxing and Unboxing ConversionsAll primitive-type Structures inherit from class ValueType (namespace System). Class ValueType inherits from class Object. Thus, any primitive-type value can be assigned to an Object variable; this is referred to as boxing. With boxing, a primitive-type value is copied into an object so that the primitive-type value can be manipulated as an Object. Boxing can be performed either explicitly or implicitly, as shown in the following statements: Dim i As Integer = 5 ' create an Integer value Dim object1 As Object = _ CType(i, Object) ' explicitly box the Integer value Dim object2 As Object = i ' implicitly box the Integer value After executing the preceding code, both object1 and object2 refer to two different objects that contain a copy of the integer value in Integer variable i. Unboxing can be used to explicitly convert an Object reference to a primitive value, as shown in the following statement: ' explicitly unbox the Integer value Dim int1 As Integer = CType(object1, Integer) Explicitly attempting to unbox an Object reference that does not refer to the correct primitive value type causes an InvalidCastException. In Chapters 25 and 26, we discuss Visual Basic's generics and .NET's generic collections. As you will see, generics eliminate the overhead of boxing and unboxing by enabling us to create and use collections of specific value types. |