Home
Map
Cast: TryCast, DirectCast ExamplesUse TryCast and DirectCast. Handle invalid casts and view casting syntax.
VB.NET
This page was last reviewed on Dec 9, 2022.
TryCast. Casting syntax is language-specific. In casting, we convert one type to a more, or less, derived type. Often we cast from Object, the ultimate base class.
Invalid casts. 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.
An example. Let us explore casts. Here we use TryCast() in a VB.NET program. TryCast attempts to cast but handles failure more gracefully.
Part 1 This example creates a String Dim and then references it with an Object Dim.
Part 2 We invoke TryCast to cast the Object back to a String. The first argument to TryCast is an Object.
And The last Dim, valueString, is again a String variable. So we can call Length on it.
String Length
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 Module
3
An 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.
Nothing
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 Module
TryCast 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 Module
4
A 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 Module
Value 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.
StringBuilder
Detail 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 Module
Unhandled Exception: System.InvalidCastException: Unable to cast object of type 'System.String' to type 'System.Text.StringBuilder'.
Performance. My top casting performance tip is not to cast. In performance optimization, avoiding actions is usually the best strategy. Try to keep data in its more useful type.
Detail Consider using generic types, like List or Dictionary, instead of ArrayList or Hashtable. Less casting is needed.
List
Dictionary
ArrayList
Hashtable
Another tip. 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.
Conversions. Casting does not handle converting units. For example, a conversion from miles to kilometers will require a special conversion function.
A review. 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.
No updates found for this page.
Home
Changes
© 2007-2024 Sam Allen.