Convert.ToInt32() vs Int32.Parse() in C#

Convert.ToInt32() vs Int32.Parse() in C#

First of all, calling Int32.Parse is faster than calling Convert.ToInt32 method.

Secondly, Convert.ToInt32 takes an object as an argument and checks for null values. That's why it's not throwing ArgumentNullException, and is a bit slower.

We will give more details about the comparison of Convert.ToInt32() and Int32.Parse() in the next paragraphs.

Int32.Parse

If you've got a string, and you expect it to always be an integer (say, if some web service is handing you an integer in string format), you'd use Int32.Parse(). Here is the Int32.Parse command taken from reflector:

public static int Parse(string s)
{
    return System.Number.ParseInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
}

Int32.TryParse

If you're collecting input from a user, you'd generally use Int32.TryParse(), since it allows you more fine-grained control over the situation when the user enters invalid input.

Convert.ToInt32

Convert.ToInt32() takes an object as its argument. Convert.ToInt32() also does not throw ArgumentNullException when its argument is null the way Int32.Parse() does. That also means that Convert.ToInt32() is probably a bit slower than Int32.Parse(). Here is the Convert.ToInt32 command taken from reflector:

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


added 6 years 5 months ago

- How to POST and GET url with parameters in C#?
- Open a text file and read line by line in C#
- Convert.ToInt32() vs Int32.Parse() in C#
- How to C# Linq Group By by paramater/field names
- Simple Injector
- How to check memory consumption in c#
- How can I implement C/C++ "union" in C#?
- How to Open and Read From Excel File in C#
- Weak References
- Lazy Initialization
- Enable Nuget Package Restore
- OnixS FIX Engine
- Rapid Addition FIX API
- How to change DateTime format in C#
- How to change number decimal seperator in C#?
2
1