asting, or converting the value of a token from one type of data to another is common to most (if not all) programming languages. Visual Basic has long had a series of casting functions, such as CStr
, etc. to allow conversion of one type of variable to another. While the idea of casting is simple and familiar when discussed in the context of a simple variable containing a value (.NET value types), the meaning and behavior of a cast is less clear when discussed in the context of objects.
Casting is the term used to describe the conversion of a value from one data type to another. In principle this is fairly straightforward to most experienced programmers. A String of "12" can be converted to an Integer of 12. A Date value of 12/07/41 can be converted to a String of "12/07/41" or even "December 7, 1941".
Variables in .NET languages are referred to as "types", and there are two types that you need to concern yourself with in any .NET language: value types and reference types. Value types are the simpler, or at least the more familiar of the two. Value types include Boolean and numeric values (Float, Long, Double, Integer), Date, and DateTime values. Value types are all based on structures rather than classes. Structures are stored on the memory stack rather than the heap and cannot be subclassed. Integer types are based on the System.Int32 structure, Long types are based on System.Int64, Boolean types are based on System.Boolean, DateTime types are based on System.DateTime, and so forth. The base value type structures derive from System.ValueType, which is in turn derived from System.Object.
|Figure 1: The hierarchy of value types and reference types.|
Reference types are all derived from the System.Object class, not from the derived System.ValueType. .NET stores reference types on the memory heap, rather than the stack, and include not only what you might think of as objects, that is, instances of your own custom classes (as well as the other couple of thousand .NET classes), but also more complex native data representations such as arrays and strings. Figure 1
illustrates these relationships.
This article discusses how casting reference types actually works, and how you can take advantage of casting when interacting with class instances. Understanding this diagram is important if you want to understand the differences between casting value types and casting reference types.