While converting types, I have found myself using both VB functions and BCL Convert.To* methods.
E.g.)
Cstr()
vs. Convert.ToString()
CInt()
vs. Convert.ToInt32()
CDbl()
vs. Convert.ToInt64()
Are there any subtle differences that should be noted?
Conversion functions allow you to convert a known value to a another type. Besides these functions, the Visual Basic language provides a function named CType. Its syntax is: CType(expression, typename) As you can see, the CType() function takes two arguments.
To do this, use the ToString(IFormatProvider) and Parse(String, IFormatProvider) methods of that value's type. For example, use Double. Parse when converting a string to a Double , and use Double.
1. In type casting, a data type is converted into another data type by a programmer using casting operator. Whereas in type conversion, a data type is converted into another data type by a compiler.
Type Conversions in Visual Basic The process of changing a value from one data type to another type is called conversion. Conversions are either widening or narrowing, depending on the data capacities of the types involved. They are also implicit or explicit, depending on the syntax in the source code.
There is another big difference that I've just discovered and I think is worth mentioning here – albeit several years after the OP! CInt({Boolean expression})
evaluates to -1 when True
, whereas Convert.ToInt<n>
evaluates to 1.
This could catch anyone out who's used the former in a math evaluations, EG:
For i As Integer = 0 To 1 - CInt(processThirdItem) 'Evaluates to -1 (1 - -1 = 2)
'Do stuff...
Next
So, using Convert.ToInt32
in place of CInt
wouldn't work unless you changed the operator from -
to +
.
Of course .NET's short-circuited If
function now provides a much better way to do this:
For i As Integer = 0 to If(processThirdItem, 2, 1)
'Do stuff...
Next
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With