11

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?

th1rdey3
  • 4,176
  • 7
  • 30
  • 66

4 Answers4

17

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.

Tigran
  • 61,654
  • 8
  • 86
  • 123
7

Basically Convert.ToInt32 uses 'Int32.Parse' behind scenes but at the bottom line Convert.ToInt32 A null will return 0. while in Int32.Parse an Exception will be raised.

ronen
  • 1,460
  • 2
  • 17
  • 35
3

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.

Sachin
  • 40,216
  • 7
  • 90
  • 102
2

Convert.ToInt32 (string value)

From MSDN:

Returns a 32-bit signed integer equivalent to the value of value. -or- Zero if value is a null reference (Nothing in Visual Basic). The return value is the result of invoking the Int32.Parse method on value.

jlvaquero
  • 8,571
  • 1
  • 29
  • 45