简体   繁体   中英

c# : int.Parse not working correctly

I implemented the following method in c#, to check if the user-entered number is a 10 digit number or not. It is working fine for an input number of upto 10 digits. But, when I enter a number of greater than 10 digits it prints Given string does not represent a number instead of The length of the Contact No. is not 10

I know that I can do the same thing using regex-matching, but I just want to do it by using throwing exceptions. Any help is appreciated.

    public static bool CheckContactNo(string ContactNo)
    {
        try
        {
            int Number = int.Parse(ContactNo);
            int IsZero = ContactNo.Length == 10 ? 1 : 0;
            //Console.WriteLine("{0}",IsZero);
            int somenum = 1/ IsZero;
            return true;
        }
        catch(DivideByZeroException)
        {
            Console.WriteLine("The length of the Contact No. is not 10");
            return false;
        }

        catch (Exception)
        {
            Console.WriteLine("Given string does not represent a number");
            return false;
        }
    }

A 32-bit int cannot hold 10 full digits, its max value is 2,147,483,647 .

In other words, int.Parse detects that your int would overflow, and gives that error.

Int32.MaxValue is 2,147,483,647 . You won't be able to parse numbers larger than int.maxvalue.

In addition to Joachim's answer (where the solution is to use Int64 ), I would also not use exceptions (like DivZero) to control flow in that way, instead prefer to use validations like TryParse to determine whether the value is numeric:

if (contactNo.Length != 10)
{
    Console.WriteLine("The length of the Contact No. is not 10");       
}
else
{
    long contactLong;

    if (Int64.TryParse(ContactNo, out contactLong)
    {
        return true;
    }
    else
    {
        Console.WriteLine("Given string does not represent a number");
    }
}
return false;

您可以使用Int64而不是int

这(2,147,483,647)是Int32的最大值,因此int.Parse在内部对此进行检查您可以使用Int64.Parse

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM