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?
+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
2009-02-25 19:53:58
+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
2009-02-25 19:54:36
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
2009-02-25 19:55:16
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
2009-02-25 19:55:34
No, TryParse definitely doesn't do a try{}catch{}. It's much faster (for invalid data) than calling Parse yourself.
Jon Skeet
2009-02-25 21:30:43