19.2 Simple-Type structs, Boxing and Unboxing

The data structures we discuss in this chapter store object references. As you’ll soon see, we’re able to store both simple- and reference-type values in these data structures. This section discusses the mechanisms that enable simple-type values to be manipulated as objects.

Simple-Type structs

Each simple type (see Appendix B) has a corresponding struct in namespace System that defines the simple type. These structs are called Boolean, Byte, SByte, Char, Decimal, Double, Single, Int16, UInt16 Int32, UInt32, Int64 and UInt64. Types declared with keyword struct are value types.

Simple types are actually aliases for their corresponding structs, so a variable of a simple type can be declared using either the keyword for that simple type or the struct name—e.g., int and Int32 are interchangeable. The methods related to a simple type are located in the corresponding struct (e.g., method Parse, which converts a string to an int value, is located in struct Int32). Refer to the documentation for the corresponding struct type to see the methods available for manipulating values of that type.

Boxing and Unboxing Conversions

Simple types and other structs inherit from class ValueType in namespace System. Class ValueType inherits from class object. Thus, any simple-type value can be assigned to an object variable; this is referred to as a boxing conversion and enables simple types to be used anywhere objects are expected. In a boxing conversion, the simple-type value is copied into an object so that the simple-type value can be manipulated as an object. Boxing conversions can be performed either explicitly or implicitly as shown in the following statements:


int i = 5; // create an int value
object object1 = (object) i; // explicitly box the int value
object object2 = i; // implicitly box the int value

After executing the preceding code, both object1 and object2 refer to two different objects that contain a copy of the integer value in int variable i.

An unboxing conversion can be used to explicitly convert an object reference to a simple value, as shown in the following statement:


int int1 = (int) object1; // explicitly unbox the int value

Explicitly attempting to unbox an object reference that does not refer to the correct simple value type causes an InvalidCastException.

In Chapters 20 and 21, we discuss C#’s generics and generic collections where you’ll see that you can create data structures of specific value types so that you do not need boxing and unboxing conversions.

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

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