Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better use int.Parse or Convert.ToInt32 [duplicate]

Possible Duplicate:
Whats the main difference between int.Parse() and Convert.ToInt32

I would like to know what are PRO and CONS of using Convert.ToInt32 VS int.Parse.

Here an example of syntax I am using:

            int myPageSize = Convert.ToInt32(uxPageSizeUsersSelector.SelectedValue);

            int myPageSize = int.Parse(uxPageSizeUsersSelector.SelectedValue);

I also found out these articles, maybe they can help for a discussion:

  • http://dotnetperls.com/int-parse
  • http://aspdotnethacker.blogspot.com/2010/04/difference-between-int32parsestring.html
  • http://aspdotnethacker.blogspot.com/p/visual-studio-performance-wizard.html
like image 460
GibboK Avatar asked Oct 18 '10 15:10

GibboK


1 Answers

Convert.ToInt32 is for dealing with any object that implements IConvertible and can be converted to an int. Also, Convert.ToInt32 returns 0 for null, while int.Parse throws a ArgumentNullException.

int.Parse is specifically for dealing with strings.

As it turns out, the string type's IConvertible implementation merely uses int.Parse in its ToInt32 method.

So effectively, if you call Convert.ToIn32 on a string, you are calling int.Parse, just with slightly more overhead (a couple more method calls).

This is true for any conversion from string to some primitive type (they all call Parse). So if you're dealing with strongly-typed string objects (e.g., you're parsing a text file), I'd recommend Parse, simply because it's more direct.

Converting arbitrary objects (returned to you by some external library, for instance) is the scenario where I'd opt for using the Convert class.

like image 175
Dan Tao Avatar answered Sep 29 '22 20:09

Dan Tao