Is there a better way to determine if a string can be an integer other than try/catch?
c#, validation
Solution
if (int.TryParse(string, out result))
{
// use result here
}
Problem
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; } } ```