CTypeDynamic

Posted Mon, Jan 25 2010 14:27 by bill

There’s a new function in VB 10 called CTypeDynamic .

(note it is a function not a keyword so the Microsoft.VisualBasic namespace needs to be imported)

The CTypeDynamic function looks for dynamic information and performs the cast/conversion appropriately. This is different from the CType operator which looks for static information at compile time or relies on the types being IConvertible etc.  For example, consider the following simple class with a custom narrowing operator to String:

 

Class Foo

   Public Name As String

   Public Shared Narrowing Operator CType(ByVal instance As Foo) As String
       
 Return instance.Name
   End Operator
End Class

 

If you were to create an object instance of Foo, you’d find you couldn’t cast it to string with CType. This code fails:

 

      Dim f As Object = New Foo() With {.Name = "Bar"}

      Dim s As String = CType(f, String)

 

But if you use CTypeDynamic the code works:

 

      Dim f As Object = New Foo() With {.Name = "Bar"}

      Dim s As String = CTypeDynamic(Of String)(f)

 

The difference is the CTypeDynamic examines the object at runtime including looking for Shared (aka static) custom operators. The CType operator would only work in this case if f was explicitly dimensioned as type Foo or cast to it.  That is, for CType to work with custom operators the type of the original object must be expressed in code before calling CType, eg:      
  
Dim s As String = CType(DirectCast(f, Foo), String)

 

CTypeDynamic on the other hand does the work at runtime. This obviously comes at a cost as it must examine the type(s) at runtime. Hence the “Dynamic” part in it’s name.  If you know the type when writing the code, use CType, but if you need dynamic casting then you need to use CTypeDynamic.

 

 

See also “fun with dynamic objects” blog post by Doug Rothaus.

.

Filed under: , , , ,

Comments

# re: CTypeDynamic

Monday, January 25, 2010 10:33 AM by Jonathan

Thank so much for pointing that out. There were a lot of times where this would have really helped me in the past.