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

前端 未结 13 2163
-上瘾入骨i
-上瘾入骨i 2020-11-22 08:47
  • What is the main difference between int.Parse() and Convert.ToInt32()?
  • Which one is to be preferred
相关标签:
13条回答
  • 2020-11-22 08:57

    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);
            }
        }
    
    0 讨论(0)
  • 2020-11-22 09:04

    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.

    0 讨论(0)
  • 2020-11-22 09:05

    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.

    0 讨论(0)
  • 2020-11-22 09:06

    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 
    
    0 讨论(0)
  • 2020-11-22 09:09

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

    0 讨论(0)
  • 2020-11-22 09:10

    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.

    0 讨论(0)
提交回复
热议问题