CType. In VB.NET we have many ways to convert one type to another. The CType operator converts a local variable to another type, and only succeeds if the types are compatible.
Similar in ways to DirectCast and TryCast, CType is versatile and can handle both reference and value types. Unlike TryCast, CType can cause an exception, and this can cause issues.
Reference types. For testing CType and other conversion approaches, we introduce an Example class. This class (like all classes) has Object as its ultimate base class.
Class Example
Public Dim _name As String = "abc"
End Class
Module Module1
Sub Main()
Dim o As Object = New Example()
' Part 1: cast Object to Example with CType.
Dim s As Example = CType(o, Example)
Console.WriteLine(s._name)
' Part 2: use DirectCast to cast.
Dim s2 As Example = DirectCast(o, Example)
Console.WriteLine(s2._name)
' Part 3: use implicit cast expression.
Dim s3 As Example = o
Console.WriteLine(s3._name)
' Part 4: use TryCast for exception-safe casting.
Dim s4 As Example = TryCast(o, Example)
If Not IsNothing(s4)
Console.WriteLine(s4._name)
End If
End Sub
End Moduleabc
abc
abc
abc
Value types. With CType, we can also convert value types, which are specified as Structures. Types like Integer and Short are value types.
Part 1 CType allows us to cast value types like Integer and Short. This can cause an exception.
Part 2 An implicit cast can be used instead of the CType operator (and this can also cause exceptions).
Part 3 When a numeric value cannot be represented in a smaller type, an OverflowException is thrown.
Module Module1
Sub Main()
' Part 1: use CType to cast Integer to Short.
Dim value As Integer = 100
Dim v As Short = CType(value, Short)
Console.WriteLine(v)
' Part 2: use implicit cast instead of CType.
Dim v2 As Short = value
Console.WriteLine(v2)
' Part 3: use CType when the numeric cast fails, which causes an exception.
Dim value2 As Integer = Integer.MaxValue
Dim v3 As Short = CType(value2, Short)
End Sub
End Module100
100
Unhandled exception. System.OverflowException:
Arithmetic operation resulted in an overflow.
at vbtest.Module1.Main() in C:\Users\...\Program.vb:line 14
Summary. It is possible to use CType to cast from one compatible type to another. But often, using an implicit cast has the same effect (and may be easier to understand).
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Sep 6, 2024 (edit link).