views:

149

answers:

1

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?

+4  A: 

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);.

annakata
Huh: you made your edit while I was researching my post -- mostly looking for (and failing to find) the benchmark link I mentioned. It's funny because your link is the follow-up by the same author to the one I posted. If you do another edit to include both I'll delete my post in favor of yours.
Joel Coehoorn
Done, but I wouldn't be offended if you edited it in you know :)
annakata
I loved Joel's summary. Thank you
Sung Meister