Search...

Thursday, February 2, 2012

What's the difference between Int32.Parse() and Convert.ToInt()?



Int32.Parse() vs Convert.ToInt()


That's a good question, isn't it? At least, that's a question that I often hear.

Int32.Parse converts a string variable (or some other valid types) into a variable of type int. However if you pass a non-recognized value (text string, empty string or null string), it will throw an exception (System.NullArgumentException if null else System.FormatException)

Below is the code of Int32.Parse(string) using Reflector

public static int Parse(string s)
{
return int.Parse(s, NumberStyles.Integer, null);
}

It calls internally another signature of the method with all arguments


public static int Parse(string s, NumberStyles style, IFormatProvider provider)
{
NumberFormatInfo info1 = NumberFormatInfo.GetInstance(provider);
NumberFormatInfo.ValidateParseStyle(style);
return Number.ParseInt32(s, style, info1);
}

Convert.ToInt32 also converts a string (or some other valid types) into a variable of type int. It basically behaves the same way as Int32.Parse() except that it won't throw an exception System.NullArgumentException if a null string is passed to the method, instead it will return 0.

Below is the code of Convert.ToInt32(string) using Reflector

public static int ToInt32(string value)
{
if (value == null)
{
return 0;
}
return int.Parse(value);
}

No comments: