The object Class

As noted earlier, the Object class is the base class for every type in .NET, both value and reference types. At its core, every variable is an object and can be treated as such.

Because the Object class is the basis of all types, you can cast any variable to an object. Reference types maintain their current reference and implementation but are generically handled, whereas value types are taken from their current location on the stack and placed into the heap with a memory location associated with the Object. This process is called 'boxing' because you are taking the value and shipping it from one location to another. Boxing is discussed in more detail in Chapter 8.

The key addition to your understanding of Object is that if you create an implementation of ToString in your class definition, then even when an instance of your object is cast to the type Object, your custom method will still be called. The following snippet shows how to create a generic object.

Dim objVar as Object objVar = Me

CType(objVar, Form).Text = "New Dialog Title Text"

That Object is then assigned a copy of the current instance of a Visual Basic form. In order to access the Text property of the original Form class, the Object must be cast from its declared type of Object to its

Code snippet from Forml

FiGuRE 2-7

actual type (Form), which supports the Text property. The CType command (covered later) accepts the object as its first parameter, and the class name (without quotes) as its second parameter. In this case, the current instance variable is of type Form; and by casting this variable, the code can reference the Text property of the current form.

Was this article helpful?

0 0

Post a comment