ChatGPT解决这个技术问题 Extra ChatGPT

What's the main difference between int.Parse() and Convert.ToInt32

c#

What is the main difference between int.Parse() and Convert.ToInt32()?

Which one is to be preferred


C
Community

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().

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() takes an object as its argument. (See Chris S's answer for how it works) 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 wee bit slower than Int32.Parse(), though in practice, unless you're doing a very large number of iterations in a loop, you'll never notice it.


As others point out, Convert.ToInt32(s) doesn't throw an exception when s is null, but Parse() does. "A bit slower" is completely beside the point as you'll never measure the difference.
Thanks, Robert! I'm editing my answer for some more completeness. But as far as performance goes, I'll bet the difference in speed would be detectable if you're calling it in a nested loop...
Actually, since the ToInt32 method has an overload for loads of types, there among them System.String, no time will be lost discerning the type. The actual code does nothing but return 0 for null values, and int.Parse(value, CultureInfo.CurrentCulture) for everything else.
@StealthRabbi: In the "Return value" section of the documentation: "A 32-bit signed integer that is equivalent to the number in value, or 0 (zero) if value is null."
please remove your mention of Int32.TryParse() in Convert.ToInt32() because it is incorrect. Convert throws an exception if the string is formatted incorrectly.
C
Chris S

Have a look in reflector:

int.Parse("32"):

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

which is a call to:

internal static unsafe int ParseInt32(string s, NumberStyles style, NumberFormatInfo info)
{
    byte* stackBuffer = stackalloc byte[1 * 0x72];
    NumberBuffer number = new NumberBuffer(stackBuffer);
    int num = 0;
    StringToNumber(s, style, ref number, info, false);
    if ((style & NumberStyles.AllowHexSpecifier) != NumberStyles.None)
    {
        if (!HexNumberToInt32(ref number, ref num))
        {
            throw new OverflowException(Environment.GetResourceString("Overflow_Int32"));
        }
        return num;
    }
    if (!NumberToInt32(ref number, ref num))
    {
        throw new OverflowException(Environment.GetResourceString("Overflow_Int32"));
    }
    return num;
}

Convert.ToInt32("32"):

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

As the first (Dave M's) comment says.


Thanks for removing all the conjecture from the prior answer.
shouldn't it be "return default(int);" ?
In short, Convert.ToInt32 returns 0 if null to prevent int.Parse from raising an ArgumentNullException.
@SkorunkaFrantišek - The expression default(int) is evaluated at compile time, since its an intrinsic value - the result of the expression is 0, so the compiler inserts a literal 0. The IL disassembly tools can't know any better, so they just show you a literal zero.
@SkorunkaFrantišek This is entirely besides the point. The user was copying reflected code. To change it would be an incorrect representation of what is compiled. If the user had original source and the original source had default(int) then that is what the user would have posted.
L
Lachlan Goodhew-Cook

No difference as such.
Convert.ToInt32() calls int.Parse() internally

Except for one thing Convert.ToInt32() returns 0 when argument is null

Otherwise both work the same way


More precisely, Convert.ToInt32(string) calls int.Parse internally. Convert.ToInt32(object), however, calls ((IConvertible) value).ToInt32, which in the case of string calls Convert.ToInt32(string)... a bit convoluted...
Yeah, Convert.ToInt32(char) will actually return (int)value, which will turn '1' into 49. Not generally the intended functionality.
R
Ranjithkumar

int.Parse(string s)

Integer in RANGE > returns integer value

Null value > ArguementNullException

Not in format > FormatException

Value not in RANGE > OverflowException

Convert.ToInt32(string s)

Integer in RANGE > returns integer value

Null value > returns "0"

Not in format > FormatException

Value not in RANGE > OverflowException

bool isParsed = int.TryParse(string s,out res)

Integer in RANGE > returns integer value, isParsed = true

Null value > returns "0", isParsed = false

Not in format > returns "0", isParsed = false

Value not in RANGE > returns "0", isParsed = false

Try this code below.....

class Program
{
    static void Main(string[] args)
    {
        string strInt = "24532";
        string strNull = null;
        string strWrongFrmt = "5.87";
        string strAboveRange = "98765432123456";
        int res;
        try
        {
            // int.Parse() - TEST
            res = int.Parse(strInt); // res = 24532
            res = int.Parse(strNull); // System.ArgumentNullException
            res = int.Parse(strWrongFrmt); // System.FormatException
            res = int.Parse(strAboveRange); // System.OverflowException

            // Convert.ToInt32(string s) - TEST
            res = Convert.ToInt32(strInt); // res = 24532
            res = Convert.ToInt32(strNull); // res = 0
            res = Convert.ToInt32(strWrongFrmt); // System.FormatException
            res = Convert.ToInt32(strAboveRange); //System.OverflowException

            // int.TryParse(string s, out res) - Test
            bool isParsed;
            isParsed = int.TryParse(strInt, out res); // isParsed = true, res = 24532
            isParsed = int.TryParse(strNull, out res); // isParsed = false, res = 0
            isParsed = int.TryParse(strWrongFrmt, out res); // isParsed = false, res = 0
            isParsed = int.TryParse(strAboveRange, out res); // isParsed = false, res = 0 
        }
        catch(Exception e)
        {
            Console.WriteLine("Check this.\n" + e.Message);
        }
    }

very useful summary , thanks!
R
Roman Starkov

The difference is this:

Int32.Parse() and Int32.TryParse() can only convert strings. Convert.ToInt32() can take any class that implements IConvertible. If you pass it a string, then they are equivalent, except that you get extra overhead for type comparisons, etc. If you are converting strings, then TryParse() is probably the better option.


T
T.Todua

Int32.parse(string)--->

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. If s is other than integer value, it will throw FormatException. When s represents a number less than MinValue or greater than MaxValue, it will throw OverflowException. For example:

string s1 = "1234"; 
string s2 = "1234.65"; 
string s3 = null; 
string s4 = "123456789123456789123456789123456789123456789"; 

result = Int32.Parse(s1);    //1234
result = Int32.Parse(s2);    //FormatException
result = Int32.Parse(s3);    //ArgumentNullException 
result = Int32.Parse(s4);    //OverflowException

Convert.ToInt32(string) --> 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 s is other than integer value, it will throw FormatException. When s represents a number less than MinValue or greater than MaxValue, it will throw OverflowException.

For example:

 result = Convert.ToInt32(s1);    // 1234 
 result = Convert.ToInt32(s2);    // FormatException
 result = Convert.ToInt32(s3);    // 0
 result = Convert.ToInt32(s4);    // OverflowException 

M
Michel Ayres

TryParse is faster...

The first of these functions, Parse, is one that should be familiar to any .Net developer. This function will take a string and attempt to extract an integer out of it and then return the integer. If it runs into something that it can’t parse then it throws a FormatException or if the number is too large an OverflowException. Also, it can throw an ArgumentException if you pass it a null value. TryParse is a new addition to the new .Net 2.0 framework that addresses some issues with the original Parse function. The main difference is that exception handling is very slow, so if TryParse is unable to parse the string it does not throw an exception like Parse does. Instead, it returns a Boolean indicating if it was able to successfully parse a number. So you have to pass into TryParse both the string to be parsed and an Int32 out parameter to fill in. We will use the profiler to examine the speed difference between TryParse and Parse in both cases where the string can be correctly parsed and in cases where the string cannot be correctly parsed. The Convert class contains a series of functions to convert one base class into another. I believe that Convert.ToInt32(string) just checks for a null string (if the string is null it returns zero unlike the Parse) then just calls Int32.Parse(string). I’ll use the profiler to confirm this and to see if using Convert as opposed to Parse has any real effect on performance.

Source with examples

Hope this helps.


When you look at the source from TryParse it actually has no exception handling at all - just character manipulation and bit shifting, thanks for the link
According to these benchmarks, Parse, TryParse, and Convert are pretty much the same speed unless you're converting more than 2 million objects.
T
Tisho
Convert.ToInt32

has 19 overloads or 19 different ways that you can call it. Maybe more in 2010 versions.

It will attempt to convert from the following TYPES;

Object, Boolean, Char, SByte, Byte, Int16, UInt16, Int32, UInt32, Int64, UInt64, Single, Double, Decimal, String, Date

and it also has a number of other methods; one to do with a number base and 2 methods involve a System.IFormatProvider

Parse on the other hand only has 4 overloads or 4 different ways you can call the method.

Integer.Parse( s As String)

Integer.Parse( s As String,  style As System.Globalization.NumberStyles )

Integer.Parse( s As String, provider As System.IFormatProvider )

Integer.Parse( s As String,  style As System.Globalization.NumberStyles, provider As System.IFormatProvider )

Y
Yes Barry

Convert.ToInt32 allows null value, it doesn't throw any errors Int.parse does not allow null value, it throws an ArgumentNullException error.


D
Dale K

It depends on the parameter type. For example, I just discovered today that it will convert a char directly to int using its ASCII value. Not exactly the functionality I intended...

YOU HAVE BEEN WARNED!

public static int ToInt32(char value)
{
    return (int)value;
} 

Convert.ToInt32('1'); // Returns 49
int.Parse('1'); // Returns 1

Can char convert implicitly to string in C#? It certainly can in VB.NET, and so programmers in that language would likely expect Convert.ToInt32("1"c) and Convert.ToInt32("1") to be equivalent, but I don't think C# has that implicit conversion.
You cannot convert char to string, either implicitly or explicitly. You would need to call '1'.ToString() or new string('1', 1);
I wouldn't consider the "warning" terribly significant for C#, since that language regards char values as being a bit more number-ish than vb.net. The danger would be greater in vb.net, where there because of an implicit cast there's less of a perceived difference between Char and String.
N
NightOwl888

Here is a detail for int.Parse and Convert.ToInt32: Say, you have a char array, char[] a=['1','2','3','4'] and want to convert each element into an integer. The Convert.ToInt32(a[0]) will give you a number of 49. It treats it as ASCII code The int.Parse(a[0]) will give you the right output which is 1

If you have a string array string[] b=['1','2','3','4'], then Convert.ToInt32 and int.Parse will have no difference in output. Both return the right integer.


S
Sylwester Santorowski

Parse() methods provide the number styles which cannot be used for Convert(). For example:

int i;
bool b = int.TryParse( "123-",
           System.Globalization.NumberStyles.AllowTrailingSign,
           System.Globalization.CultureInfo.InvariantCulture,
           out i);

would parse the numbers with trailing sign so that i == -123 The trailing sign is popular in ERP systems.


u
user854301

for clarification open console application, just copy below code and paste it in static void Main(string[] args) method, I hope you can understand

public  class Program
    {
        static void Main(string[] args)
        { 
            int result;
            bool status;
            string s1 = "12345";
            Console.WriteLine("input1:12345");
            string s2 = "1234.45";
            Console.WriteLine("input2:1234.45");
            string s3 = null;
            Console.WriteLine("input3:null");
            string s4 = "1234567899012345677890123456789012345667890";
            Console.WriteLine("input4:1234567899012345677890123456789012345667890");
            string s5 = string.Empty;
            Console.WriteLine("input5:String.Empty");
            Console.WriteLine();
            Console.WriteLine("--------Int.Parse Methods Outputs-------------");
            try
            {
               result = int.Parse(s1);

               Console.WriteLine("OutPut1:" + result);
            }
            catch (Exception ee)
            {
                Console.WriteLine("OutPut1:"+ee.Message);
            }
            try
            {
              result = int.Parse(s2);

              Console.WriteLine("OutPut2:" + result);
            }
            catch (Exception ee)
            {
                Console.WriteLine("OutPut2:" + ee.Message);
            }
            try
            {
               result = int.Parse(s3);

               Console.WriteLine("OutPut3:" + result);
            }
            catch (Exception ee)
            {
                Console.WriteLine("OutPut3:" + ee.Message);
            }
            try
            {
                result = int.Parse(s4);

                Console.WriteLine("OutPut4:" + result);
            }
            catch (Exception ee)
            {
                Console.WriteLine("OutPut4:" + ee.Message);
            }

            try
            {
                 result = int.Parse(s5);

                 Console.WriteLine("OutPut5:" + result);
            }
            catch (Exception ee)
            {
                Console.WriteLine("OutPut5:" + ee.Message);
            }
            Console.WriteLine();
            Console.WriteLine("--------Convert.To.Int32 Method Outputs-------------");
            try
            {

                result=  Convert.ToInt32(s1);

                Console.WriteLine("OutPut1:" + result);
            }
            catch (Exception ee)
            {
                Console.WriteLine("OutPut1:" + ee.Message);
            }
            try
            {

                result = Convert.ToInt32(s2);

                Console.WriteLine("OutPut2:" + result);
            }
            catch (Exception ee)
            {
                Console.WriteLine("OutPut2:" + ee.Message);
            }
            try
            {

         result = Convert.ToInt32(s3);

         Console.WriteLine("OutPut3:" + result);
            }
            catch (Exception ee)
            {
                Console.WriteLine("OutPut3:" + ee.Message);
            }
            try
            {

                  result = Convert.ToInt32(s4);

                  Console.WriteLine("OutPut4:" + result);
            }
            catch (Exception ee)
            {
                Console.WriteLine("OutPut4:" + ee.Message);
            }

            try
            {

                 result = Convert.ToInt32(s5);

                 Console.WriteLine("OutPut5:" + result);
            }
            catch (Exception ee)
            {
                Console.WriteLine("OutPut5:" + ee.Message);
            }

            Console.WriteLine();
            Console.WriteLine("--------TryParse Methods Outputs-------------");
            try
            {

                status = int.TryParse(s1, out result);
                Console.WriteLine("OutPut1:" + result);
            }
            catch (Exception ee)
            {
                Console.WriteLine("OutPut1:" + ee.Message);
            }
            try
            {

                status = int.TryParse(s2, out result);
                Console.WriteLine("OutPut2:" + result);
            }
            catch (Exception ee)
            {
                Console.WriteLine("OutPut2:" + ee.Message);
            }
            try
            {

                status = int.TryParse(s3, out result);
                Console.WriteLine("OutPut3:" + result);
            }
            catch (Exception ee)
            {
                Console.WriteLine("OutPut3:" + ee.Message);
            }
            try
            {

                status = int.TryParse(s4, out result);
                Console.WriteLine("OutPut4:" + result);
            }
            catch (Exception ee)
            {
                Console.WriteLine("OutPut4:" + ee.Message);
            }

            try
            {

                status = int.TryParse(s5, out result);
                Console.WriteLine("OutPut5:" + result);
            }
            catch (Exception ee)
            {
                Console.WriteLine("OutPut5:" + ee.Message);
            }


            Console.Read();
        }
    }