Type Conversions in VB.NET
In this article I will explain you about type conversion in VB.NET.
Conversion allows you to treat one type as another. For example, storing an integer value in a long variable constitutes conversion from integer to a long. VB supports limited implicit conversions as well as explicit conversions.
With implicit conversions, you pass a type to another type without losing any data. Conversion from short to long-or from int to long, in the case that follows-is an example of implicit conversion.
Dim num1 As Integer = 34
Dim num2 As Long = a
Implicit conversion is only possible when you pass a small-range type to a big-range type. A long data type can hold short and int values with no problem, but the reverse is not true without risking data loss. Some of the implicit conversions are as follows:
-
From sbyte to short, int, long, float, double, or decimal.
-
From byte to short, ushort, int, uint, long, ulong, float, double, or decimal.
-
From short to int, long, float, double, or decimal.
-
From ushort to int, uint, long, ulong, float, double, or decimal.
-
From int to long, float, double, or decimal.
-
From uint to long, ulong, float, double, or decimal.
-
From long to float, double, or decimal.
-
From ulong to float, double, or decimal.
-
From char to ushort, int, uint, long, ulong, float, double, or decimal.
-
From float to double.
In explicit conversions, you must cast a type with another type to pass data between them. For example, conversion from long to int is handled explicitly, as follows:
Dim num1 As Long = 3443
Dim num2 As Integer = CInt(a)
Some possible explicit conversions are as follows:
-
From sbyte to byte, ushort, uint, ulong, or char.
-
From byte to sbyte or char.
-
From short to sbyte, byte, ushort, uint, ulong, or char.
-
From ushort to sbyte, byte, short, or char.
-
From int to sbyte, byte, short, ushort, uint, ulong, or char.
-
From uint to sbyte, byte, short, ushort, int, or char.
-
From long to sbyte, byte, short, ushort, int, uint, ulong, or char.
-
From ulong to sbyte, byte, short, ushort, int, uint, long, or char.
-
From char to sbyte, byte, or short.
-
From float to sbyte, byte, short, ushort, int, uint, long, ulong, char, or decimal.
-
From double to sbyte, byte, short, ushort, int, uint, long, ulong, char, float, or decimal.
-
From decimal to sbyte, byte, short, ushort, int, uint, long, ulong, char, float, or double.
However, prudent testing is always advisable to determine whether a conversion will cause loss of data or the unexpected conversion of values.
Conclusion
See other articles on the website on VB.NET.