TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to VBNET

VB.NET Cast: TryCast, DirectCast Examples

Use TryCast and DirectCast. Handle invalid casts and view casting syntax.
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.
Let us explore casts. This example creates a String Dim and then references it with an Object Dim. We then invoke TryCast to cast the Object back to a String.

Result: The last Dim, valueString, is again a String variable. So we can call Length on it.

String Length
VB.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
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 in reality.

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.

Nothing
VB.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
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.

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
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.

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'.
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

TryCast: 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'.
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.

Generics: Consider using generic types, like List or Dictionary, instead of ArrayList or Hashtable. Less casting is needed.

ListDictionaryArrayListHashtable
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.Convert Miles, Kilometers
A review. Major advances in programming languages have been driven by the desire to reduce casting. Generics (parameterized types) minimize casting. This increases performance.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf