tags:

views:

210

answers:

5

A question that came to one of my colleagues mind, what is the best way to check if a query string is an int. I suggested using the classic Int.Parse and try and catch, also TryParse was suggested. Actually i can't think of any other ways. Any ideas?

+12  A: 

Int32.TryParse is going to be your best bet.

Andrew Hare
+2  A: 

TryParse is probably your best bet, since it will allow for different formats for the string, as well as tell you through a boolean value whether or not it is valid.

casperOne
+1  A: 

I like Int32.TryParse. You could use a regex instead I suppose, but I'm not sure there would be any point.

Kevin Tighe
A: 

Probably not too useful since you'd likely want the actual int (though it could be extended to do that). NOTE: I wouldn't do this, but it IS an alternate way that he hadn't thought of.

bool isNumeric = true;
foreach (char c in queryString) {
    if (!char.IsDigit(c)) {
       isNumeric = false;
       break;
    }
}
tvanfosson
A: 

I prefer the TryParse method. Both are just about equal, I believe TryParse does a try{}catch{} inside of the method so I doubt there's much difference in execution.

palehorse
No, TryParse definitely doesn't do a try{}catch{}. It's much faster (for invalid data) than calling Parse yourself.
Jon Skeet