Discussion

  • Thread starter Thread starter Paul
  • Start date Start date
P

Paul

string mynumberstring = "123";
int mynumber;
mynumber = int.Parse(mynumberstring);
mynumber = Convert.ToInt32(mynumberstring);

Both seem to have the same effect. But whats the
difference and which is 'best'?

Thanks, Paul.
 
Paul,

Int32.Parse has the most flexibility, with the capability of passing in
a string, a value from the NumberStyles enumeration, and a format provider.
ToInt32 will only accept the string and a format provider. The Convert
class has the advantage of being able to take any type and trying to convert
to an Int32 (not always successful though).

So, you should pick the one that suits your needs best and then use
that. I don't know if there is a perf difference, but I am sure someone can
run some tests.

Hope this helps.
 
Paul,

I ran my own tests (just a loop), and I ran each one for ten million
times. I found there to be a slight advantage in the call to Int32.Parse,
by about .2 - .4 seconds. Unless you are doing an ungodly amount of
conversions, I wouldn't worry about it.
 
Back
Top