Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

*Subtle* Differences between VB functions and Convert.To* functions?

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()
  • etc...

Are there any subtle differences that should be noted?

like image 398
dance2die Avatar asked Feb 19 '09 16:02

dance2die


People also ask

What is conversion function in Visual Basic?

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.

How to convert string to Double in vb net?

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.

What is the difference between cast and convert in C#?

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.

Why do we use type conversion in VB net?

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.


1 Answers

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 
like image 124
Ants1060 Avatar answered Sep 27 '22 20:09

Ants1060