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.
For testing CType
and other conversion approaches, we introduce an Example class
. This class
(like all classes) has Object as its ultimate base class
.
CType
is successful here.class
) DirectCast
can be used in the same way as CType
.TryCast
allows us to cast without causing exceptions. A Nothing value is returned if the cast does not succeed.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
With CType
, we can also convert value types, which are specified as Structures. Types like Integer and Short
are value types.
CType
allows us to cast value types like Integer and Short
. This can cause an exception.CType
operator (and this can also cause exceptions).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
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).