TryCast Operator (Visual Basic)


Updated: July 20, 2015

For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

Introduces a type conversion operation that does not throw an exception.

If an attempted conversion fails, CType and DirectCast both throw an InvalidCastException error. This can adversely affect the performance of your application. TryCast returns Nothing, so that instead of having to handle a possible exception, you need only test the returned result against Nothing.

You use the TryCast keyword the same way you use the CType Function and the DirectCast Operator keyword. You supply an expression as the first argument and a type to convert it to as the second argument. TryCast operates only on reference types, such as classes and interfaces. It requires an inheritance or implementation relationship between the two types. This means that one type must inherit from or implement the other.

TryCast generates a compiler error if it detects that no inheritance or implementation relationship exists. But the lack of a compiler error does not guarantee a successful conversion. If the desired conversion is narrowing, it could fail at run time. If this happens, TryCast returns Nothing.

A comparison of the type conversion keywords is as follows.

KeywordData typesArgument relationshipRun-time failure
CType FunctionAny data typesWidening or narrowing conversion must be defined between the two data typesThrows InvalidCastException
DirectCast OperatorAny data typesOne type must inherit from or implement the other typeThrows InvalidCastException
TryCastReference types onlyOne type must inherit from or implement the other typeReturns Nothing

The following example shows how to use TryCast.

  Function PrintTypeCode(ByVal obj As Object) As String
      Dim objAsConvertible As IConvertible = TryCast(obj, IConvertible)
      If objAsConvertible Is Nothing Then
          Return obj.ToString() & " does not implement IConvertible"
          Return "Type code is " & objAsConvertible.GetTypeCode()
      End If
  End Function

Widening and Narrowing Conversions
Implicit and Explicit Conversions