C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Result: The last Dim, valueString, is again a String variable. So we can call Length on it.
String LengthVB.NET program that uses TryCast
Module Module1
Sub Main()
' Get an Object that is a String.
Dim value As String = "cat"
Dim valueObject As Object = value
' Use TryCast to get back to String.
Dim valueString = TryCast(valueObject, String)
Console.WriteLine(valueString.Length)
End Sub
End Module
Output
3
And: TryCast behaves itself and simply returns Nothing. So valueString is a reference equal to Nothing—we use Is Nothing to test.
Nothing: This is similar to "null" or "nil" in other languages—the concepts are the same.
NothingVB.NET program that uses TryCast, Is 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
Output
TryCast to String failed
Here: I correctly cast an Object to its more derived type String. We end up with a String, which is not Nothing.
VB.NET program that uses DirectCast
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
Output
4
Tip: Compile-time errors are annoying. But they save us the hassle of ever running programs that are obviously incorrect.
VB.NET program that causes compile-time error
Imports System.Text
Module Module1
Sub Main()
Dim value As String = "fish"
Dim value2 As StringBuilder = DirectCast(value, StringBuilder)
End Sub
End Module
Output
Value of type 'String' cannot be converted to 'System.Text.StringBuilder'.
Note: I cast an Object to an incompatible type. A String cannot be cast to a StringBuilder. This makes no sense.
StringBuilderTryCast: Please use the TryCast method instead. Check for Nothing after invoking TryCast.
VB.NET program that causes InvalidCastException
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
Output
Unhandled Exception: System.InvalidCastException:
Unable to cast object of type 'System.String'
to type 'System.Text.StringBuilder'.
Generics: Consider using generic types, like List or Dictionary, instead of ArrayList or Hashtable. Less casting is needed.
ListDictionaryArrayListHashtableTip: Using TryCast can promote "exception-neutral" code. This reduces the risks associated with exceptions.