views:

414

answers:

5

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;
    }
}
+5  A: 

Int32.TryParse

Josef
+31  A: 
if (int.TryParse(string, out result))
{
    // use result here
}
John Saunders
And long.TryParse for 64-bit values too.
devstuff
+10  A: 

This probably won't be much faster, but at least it looks cleaner (no exception handling):

 public static bool IsAValidInteger(string strWholeNumber)
 {
     int wholeNumber;
     return int.TryParse(strWholeNumber, out wholeNumber);
 }
Jan Zich
Actually it will be significantly faster for situations where you repeatedly get invalid strings.
Jon Skeet
I suspected that. I was just about to test it ... but there no point now because since Jon Skeet has confirmed it :-)
Jan Zich
+5  A: 

You are looking for Int32.TryParse().

public void Foo(String input)
{
    Int32 number;
    if (Int32.TryParse(input, out number))
    {
        DoStuff(number);
    }
    else
    {
        HandleInvalidInput(input);
    }
}

In your specific case I would use the following.

public static Boolean IsValidInt32(String input)
{
    Int32 number;
    return Int32.TryParse(input, out number);
}
Daniel Brückner
The line if (Int32.TryParse(input, out number)should be: if (Int32.TryParse(input, out number))
RCIX
Thanks, fixed.
Daniel Brückner
A: 

The try/catch approach is a valid solution because for many types there are not TryParse methods implemented. So you revert to the basically one option left.

User
This doesn't answer the question (ie. string to integer).
Adrian Godong
It does. It tells the author there is no better option.
User
Actually for integers there is a better option as others mentioned.
Residuum