Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way to determine if a string can be an integer other than try/catch?

Tags:

c#

validation

I needed a function that simply checks if a string can be converted to a valid integer (for form validation).

After searching around, I ended up using a function I had from 2002 which works using C#1 (below).

However, it just seems to me that although the code below works, it is a misuse of try/catch to use it not to catch an error but to determine a value.

Is there a better way to do this in C#3?

public static bool IsAValidInteger(string strWholeNumber)
{
    try
    {
        int wholeNumber = Convert.ToInt32(strWholeNumber);
        return true;
    }
    catch
    {
        return false;
    }
}

Answer:

John's answer below helped me build the function I was after without the try/catch. In this case, a blank textbox is also considered a valid "whole number" in my form:

public static bool IsAValidWholeNumber(string questionalWholeNumber)
{
    int result;

    if (questionalWholeNumber.Trim() == "" || int.TryParse(questionalWholeNumber, out result))
    {
        return true;
    }
    else
    {
        return false;
    }
}
like image 443
Edward Tanguay Avatar asked Jul 08 '09 09:07

Edward Tanguay


People also ask

How do you check if a string can be converted to int?

To check if a string can be converted to an integer:Wrap the call to the int() class in a try/except block. If the conversion succeeds, the try block will fully run. If the conversion to integer fails, handle the ValueError in the except block.

How do you check if a string is an integer or int?

Checking If Given or Input String is Integer or Not Using isnumeric Function. Python's isnumeric() function can be used to test whether a string is an integer or not. The isnumeric() is a builtin function. It returns True if all the characters are numeric, otherwise False.

How do you check if a value is an integer or not?

To check if a String contains digit character which represent an integer, you can use Integer. parseInt() . To check if a double contains a value which can be an integer, you can use Math. floor() or Math.


1 Answers

if (int.TryParse(string, out result))
{
    // use result here
}
like image 122
John Saunders Avatar answered Sep 29 '22 20:09

John Saunders