Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between Convert.ToInt32 and Int32.Parse? [duplicate]

Tags:

c#

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?

like image 538
th1rdey3 Avatar asked Apr 09 '13 06:04

th1rdey3


2 Answers

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.

like image 51
Sachin Avatar answered Nov 02 '22 23:11

Sachin


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.

like image 27
Tigran Avatar answered Nov 03 '22 01:11

Tigran