Example. 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.
Part 1 We have a Double value, and we convert it to an Integer with CInt. We use CShort, CLng (for Long) and CUint (for unsigned integers).
Part 2 The CType function can have the same effect as CInt. We must specify Integer as the second argument.
Part 3 CBool and CByte can be used on small integers. We must be careful that the type can accommodate the value.
Part 4 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.