Поделиться через


TryCast Operator (Visual Basic)

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

Remarks

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 (Visual Basic), 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 (Visual Basic) and the DirectCast Operator (Visual Basic) 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 (Visual Basic).

Conversion Keywords

A comparison of the type conversion keywords is as follows.

Keyword

Data types

Argument relationship

Run-time failure

CType Function (Visual Basic)

Any data types

Widening or narrowing conversion must be defined between the two data types

Throws InvalidCastException

DirectCast Operator (Visual Basic)

Any data types

One type must inherit from or implement the other type

Throws InvalidCastException

TryCast

Reference types only

One type must inherit from or implement the other type

Returns Nothing (Visual Basic)

Example

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"
    Else
        Return "Type code is " & objAsConvertible.GetTypeCode()
    End If
End Function

See Also

Concepts

Widening and Narrowing Conversions (Visual Basic)

Implicit and Explicit Conversions (Visual Basic)