When you want to convert a string to an integer the two most popular approaches are to use int.Parse() or System.Convert.ToInt32(), both of which are static functions. (I’m not going to include int.TryParse(), System.Convert.ChangeType(), etc. in this discussion). Personally I always use int.Parse(), why? Well I don’t actually have a good reason; I’ve always just thought it looks cleaner.
So why would you choose to use one over the other? Well I guess it really depends on what you need; from my short investigation I was able to spot the following differences:
- Passing a null string into int.Parse() will throw an ArgumentNullException. Passing a null string into System.Convert.ToInt32() will return 0 (i.e. the default for int).
- int.Parse() has an overload where you can pass in the NumberStyles flags enum to specify how the string should be handled. System.Convert.ToInt32() does not have this overload.
- System.Convert.ToInt32() has an overload where you can specify the number base of the string, i.e. base 2, 8, 10, or 16.
Available overloads on int:
public static int Parse(string s) public static int Parse(string s, NumberStyles style) public static int Parse(string s, IFormatProvider provider) public static int Parse(string s, NumberStyles style, IFormatProvider provider)
Available overloads on System.Convert (for the input type string):
public static int ToInt32(string value) public static int ToInt32(string value, IFormatProvider provider) public static int ToInt32(string value, int fromBase)
Some other points for you:
- If you don’t provide the IFormatProvider both int.Parse() and Sytem.Convert.ToInt32() will retrieve the format off the CurrentCulture.
- If you do not specify the NumberStyles for int.Parse() it will simply use NumberStyles.Integer.
- System.Convert.ToInt32(string) and System.Convert.ToInt32(string, IFormatProvider) both call int.Parse() to do the conversion, where as System.Convert.ToInt32(string, int) calls ParseNumber.StringToInt(). This is a static internal class so you will need to use Red Gate’s .NET Reflector if you want to see it. Something interesting about this call is that it makes an internal call to a method in the CLR to do the conversion.
Looking at the corresponding methods for conversion on the other types it appears they seem to work in a similar way, with the exception that System.Convert.ToDouble() and System.Convert.ToDecimal() do not provide an overload to specify the number base.