Question

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?

Was it helpful?

Solution

This has been covered before in principle, but yes there are differences: basically the VB helpers will do additional work for you to get the parse through where the generics will throw an exception, and in general but not universally the VB helpers are faster (though I don't know if it's significantly so) because they're just IL sugar really. Season to taste.


Edit: This guy covers it better than I can.

Edit Redux: Joel Coehoorn also recommends the precursor to the above article, and apparently has some benchmarking up his sleeve somewhere.

Joel wrote:

The summary is the CInt() is an operator, while Convert.ToInt32() is a function. CInt lives somewhere in between (int)x; and Convert.ToInt32(x);.

OTHER TIPS

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 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top