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

前端 未结 13 2295
-上瘾入骨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);
            }
        }
    

提交回复
热议问题