TryCast Operator (Visual Basic)
Introduces a type conversion operation that does not throw an exception.
If an attempted conversion fails,
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
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.
Errors and Failures
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.
|Keyword||Data types||Argument relationship||Run-time failure|
|CType Function||Any data types||Widening or narrowing conversion must be defined between the two data types||Throws InvalidCastException|
|DirectCast Operator||Any data types||One type must inherit from or implement the other type||Throws InvalidCastException|
||Reference types only||One type must inherit from or implement the other type||Returns Nothing|
The following example shows how to use
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" Else Return "Type code is " & objAsConvertible.GetTypeCode() End If End Function