The VB.NET language provides useful type casting functions like CInt. With CInt, we convert from another type to an Integer.
Other casts like CShort
, CLng, CByte
and CBool
are available. And with CType
, we can specify the type we want to convert to as an argument.
This VB.NET program performs a variety of numeric conversions. At its end, it causes an exception to be thrown due to a cast that is not successful.
Double
value, and we convert it to an Integer with CInt. We use CShort
, CLng (for Long) and CUint
(for unsigned integers).CType
function can have the same effect as CInt. We must specify Integer as the second argument.CBool
and CByte
can be used on small integers. We must be careful that the type can accommodate the value.Double.MaxValue
cannot be represented by the bytes in an Integer, so we get an OverflowException
with CInt.Module Module1 Sub Main() ' Part 1: use CInt, CShort, CLng, and CUint. Dim value As Double = 5000 Dim result1 As Integer = CInt(value) Console.WriteLine(result1) Dim result2 As Short = CShort(value) Console.WriteLine(result2) Dim result3 As Long = CLng(value) Console.WriteLine(result3) Dim result4 As UInteger = CUInt(value) Console.WriteLine(result4) ' Part 2: use CType(Integer). Dim result5 As Integer = CType(value, Integer) Console.WriteLine(result5) ' Part 3: use CByte, and CBool with values 1 and 0. Dim value2 As Integer = 1 Dim result6 As Byte = CByte(value2) Console.WriteLine(result6) Dim result7 As Boolean = CBool(value2) Console.WriteLine(result7) Dim value3 As Integer = 0 Dim result8 As Boolean = CBool(value3) Console.WriteLine(result8) ' Part 4: if the new type cannot represent the value, we get an exception. Dim value4 As Double = Double.MaxValue Dim result9 As Integer = CInt(value4) End Sub End Module5000 5000 5000 5000 5000 1 True False Unhandled exception. System.OverflowException: Arithmetic operation resulted in an overflow. at vbtest.Module1.Main() in C:\Users\...\Program.vb:line 35
It is possible to cast values with built-in functions like CInt, CShort
, and CLng in VB.NET. But in many cases, using CType
or an implicit cast through assignment may be clearer.