Events
Mar 17, 9 PM - Mar 21, 10 AM
Join the meetup series to build scalable AI solutions based on real-world use cases with fellow developers and experts.
Register nowThis browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
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.
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 |
TryCast |
Reference types only | One type must inherit from or implement the other type | Returns 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"
Else
Return "Type code is " & objAsConvertible.GetTypeCode()
End If
End Function
.NET feedback
.NET is an open source project. Select a link to provide feedback:
Events
Mar 17, 9 PM - Mar 21, 10 AM
Join the meetup series to build scalable AI solutions based on real-world use cases with fellow developers and experts.
Register now