Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an Int.isWholeNumber() function or something similar?

Tags:

c#

validation

int

I need to check if an input is an int or not. Is there a similar function to the String.IsNullOrEmpty(), like an Int.isWholeNumber() function?

Is there a way to validate this inside the if() statement only, without having to declare an int before? (As you need to do with TryParse())

EDIT
I need to validate an area code (five numbers)

like image 302
Niklas Avatar asked Nov 28 '22 18:11

Niklas


1 Answers

I don't believe there's any such method within the BCL, but it's easy to write one (I'm assuming you're really talking about whether a string can be parsed as an integer):

public static bool CanParse(string text)
{
    int ignored;
    return int.TryParse(text, out ignored);
}

Add overloads accepting IFormatProvider values etc as you require them. Assuming this is for validation, you might want to expand it to allow a range of valid values to be specified as well...

If you're doing a lot of custom validation, you may well want to look at the Fluent Validation project.

like image 155
Jon Skeet Avatar answered Dec 04 '22 20:12

Jon Skeet