In C#
there you can convert a string to Int32 using both Int32.Parse
and Convert.ToInt32
. What's the difference between them? Which performs better? What are the scenarios where I should use Convert.ToInt32
over Int32.Parse
and vice-versa?
Int32.Parse (string s) method converts the string representation of a number to its 32-bit signed integer equivalent. When s is a null reference, it will throw ArgumentNullException.
whereas
Convert.ToInt32(string s) method converts the specified string representation of 32-bit signed integer equivalent. This calls in turn Int32.Parse () method. When s is a null reference, it will return 0 rather than throw ArgumentNullException.
If you look with Reflector or ILSpy into the mscorlib
you will see the following code for Convert.ToInt32
public static int ToInt32(string value)
{
if (value == null)
{
return 0;
}
return int.Parse(value, CultureInfo.CurrentCulture);
}
So, internally it uses the int.Parse but with the CurrentCulture
.
And actually from the code is understandable why when I specify null
like a parameter this method does not throw an exception.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With