Using the CType Function

Whether you are using late binding or not, it can be useful to pass object references around using the Object data type, converting them to an appropriate type when you need to interact with them. This is particularly useful when working with objects that use inheritance or implement multiple interfaces, concepts discussed in Chapter 3.

If Option strict is turned off, which is the default, then you can write code using a variable of type Object to make an early-bound method call:

Public sub objCType(ByVal obj As Object) Dim local As string local = obj local.ToCharArray() End sub

Code snippet from Forml

This code uses a strongly typed variable, local, to reference what was a generic object value. Behind the scenes, Visual Basic converts the generic type to a specific type so that it can be assigned to the strongly typed variable. If the conversion cannot be done, then you get a trappable runtime error.

The same thing can be done using the CType function. If Option strict is enabled, then the previous approach will not compile, and the CType function must be used. Here is the same code making use of CType:

Public sub CType1(ByVal obj As Object) Dim local As string local = CType(obj, string) local.ToLower() End sub

This code declares a variable of type TheClass, which is an early-bound data type that you want to use. The parameter you're accepting is of the generic Object data type, though, so you use the CType method to gain an early-bound reference to the object. If the object isn't of type TheClass, then the call to CType fails with a trappable error.

Once you have a reference to the object, you can call methods by using the early-bound variable local. This code can be shortened to avoid the use of the intermediate variable. Instead, you can simply call methods directly from the data type:

Public Sub CType2(obj As Object)

CType(obj, String).ToUpper() End Sub

Code snippet from Forml

Even though the variable you are working with is of type Object and therefore any calls to it will be late bound, you use the CType method to temporarily convert the variable into a specific type — in this case, the type TheClass.

If the object passed as a parameter is not of type TheClass, then you get a trappable error, so it is always wise to wrap this code in a Try...Catch block.

As shown in Chapter 3, the CType function can also be very useful when working with objects that implement multiple interfaces. When an object has multiple interfaces, you can reference a single object variable through the appropriate interface as needed by using CType.

0 0

Post a comment