TryCast. It is often necessary to cast variables in VB.NET programs. In casting, we convert one type to a more, or less, derived type. Often we cast from Object, the ultimate base class.
Some casts, like DirectCast, will throw an Exception if an invalid cast is attempted. But TryCast is safer, faster and more versatile: it simply returns Nothing.
Part 2 We invoke TryCast to cast the Object back to a String. The first argument to TryCast is an Object.
Module Module1
Sub Main()
' Part 1: get an Object that is a String.
Dim value As String = "cat"
Dim valueObject As Object = value
' Part 2: use TryCast to get back to String.
Dim valueString = TryCast(valueObject, String)
Console.WriteLine(valueString.Length)
End Sub
End Module3
Invalid cast. Next we consider what happens when we invoke TryCast on an incompatible type. Here we have a List, and try to cast it to a String. This does not work.
And TryCast behaves itself and simply returns Nothing. So valueString is a reference equal to Nothing—we use Is Nothing to test.
Detail This is similar to "null" or "nil" in other languages—the concepts are the same.
Module Module1
Sub Main()
' We are using a List of Strings.
Dim value As List(Of String) = New List(Of String)
Dim valueObject As Object = value
' Use TryCast to String, but it fails.
Dim valueString = TryCast(valueObject, String)
If valueString Is Nothing Then
Console.WriteLine("TryCast to String failed")
End If
End Sub
End ModuleTryCast to String failed
DirectCast. This casting syntax handles failure cases in a more abrupt, final way: it throws an Exception. But if our cast is valid, it works the same way as TryCast.
Here I correctly cast an Object to its more derived type String. We end up with a String, which is not Nothing.
Module Module1
Sub Main()
Dim value As String = "fish"
Dim valueObject As Object = value
' Use DirectCast to a String.
Dim valueString As String = DirectCast(valueObject, String)
Console.WriteLine(valueString.Length)
End Sub
End Module4
Compile-time error. This program will not even compile. The VB.NET compiler correctly tells us that a String cannot be cast to a StringBuilder. The types are separate.
Tip Compile-time errors are annoying. But they save us the hassle of ever running programs that are obviously incorrect.
Imports System.Text
Module Module1
Sub Main()
Dim value As String = "fish"
Dim value2 As StringBuilder = DirectCast(value, StringBuilder)
End Sub
End ModuleValue of type 'String' cannot be converted to 'System.Text.StringBuilder'.
InvalidCastException. Some casting errors are not caught by the compiler—they instead occur as runtime exceptions. Here I provoke an InvalidCastException.
Note I cast an Object to an incompatible type. A String cannot be cast to a StringBuilder. This makes no sense.
Tip Please use the TryCast method instead. Check for Nothing after invoking TryCast.
Imports System.Text
Module Module1
Sub Main()
Dim value As String = "fish"' Pass String to the Handle method.
Handle(value)
End Sub
Sub Handle(ByVal value As Object)
' Cast our argument to a StringBuilder.
Dim value2 As StringBuilder = DirectCast(value, StringBuilder)
Console.WriteLine(value2.Length)
End Sub
End ModuleUnhandled Exception: System.InvalidCastException:
Unable to cast object of type 'System.String'
to type 'System.Text.StringBuilder'.
Performance. If casting is necessary, avoid causing InvalidCastExceptions when possible. Use TryCast and check against Nothing afterwards. Exceptions are costly.
Tip Using TryCast can promote "exception-neutral" code. This reduces the risks associated with exceptions.
Summary. Major advances in programming languages have been driven by the desire to reduce casting. Generics (parameterized types) minimize casting. This increases performance.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 5, 2024 (edit link).