Type Casting in Visual Basic .NET

Provided by Molly Pell, Senior Systems Analyst

Visual Basic .NET provides two options for casting.

  • CType: Casts or converts one type into another type. If the types do not match, coercion may be performed.
  • DirectCast: Casts one type to another type with better performance than CType, but does not perform coercion if the types do not match.

Note: CType includes all of the VB conversion functions. These are CBool, CByte, CChar, CDate, CDec, CDbl, CInt, CLng, CObj, CShort, CSng, and CStr.

The main difference between the two is that DirectCast only works if the specified type and the run-time type of the expression are the same. This difference only appears when converting from an object type to a value type, or unboxing a value.

For instance, the following DirectCast operation will fail because the boxed type of the object O is not an integer:

    Dim O As Object = 1.5

    Dim I As Integer = DirectCast(O, Integer) ' Causes a run-time error.

    Dim I As Integer = CType(O, Integer) ' Does not cause a run-time error.

The DirectCast operation in this example, on the other hand, will succeed:

    Dim O As Object = 1

    Dim I As Integer = DirectCast(O, Integer) ' Succeeds.

    Dim I As Integer = CType(O, Integer) ' Succeeds, but is slower than DirectCast

When converting from an object to a value type, or unboxing, the DirectCast operator has better performance than the CType operator. The Visual Basic .NET compiler generates four lines of IL code for DirectCast. However, using CType causes the Visual Basic .NET compiler to generate a call to a conversion method that is well over one hundred lines of IL code. This method in turn calls other methods. In performance critical code, the difference can be substantial. If coercion is necessary, however, you must still use the CType operation, or perform the coercion manually.

For example:

    Dim O As Object = 1.5

    Dim f As Single = DirectCast(O, Single) ' Cast to the runtime type

    Dim i As Integer = CType(f, Integer) ' CType is OK here, since this
                                         ' cast doesn't unbox 'f'


When type casting from an object type to a value type, or unboxing, you should first determine whether type coercion is necessary. If no coercion is necessary (i.e. the boxed type of the value is the same as the type specified in the cast expression), use the DirectCast expression to increase application performance.

This tip and more detected for you with Total .NET Analyzer! See FMS .NET Analyzer for more information.

Additional Resources



Thank you! Thank you! I just finished reading this document, which was part of a link in the recent Buzz newsletter. I have printed it for others to read, especially those skeptical on the powers of Access and its capabilities.

Darren D.

View all FMS products for Microsoft Access All Our Microsoft Access Products



Free Product Catalog from FMS