C# IsNumeric
October 28th, 2009If you do a search for ‘C# IsNumeric’ you’ll find a lot of hits talking about why this function is available in VB.NET but not in C#.NET. It’s used to test if a given string can be converted to a number.
I agree it’s a very useful function and there’s lots of possible solutions, the main ones being
- Loop through the string and check each Char is a number
- Use Double.TryParse is a very popular one since it doesn’t throw an exception on failure
- Use Convert.ToInt32 inside a try/catch block
- Using a Regex expression
I really wanted to use Double.TryParse but unfortunately this will return true for numbers that are decimals. Therefore if you want to test a string for whole numbers you also have to check the string for periods or commas (using string.contains) depending on your locale.
For this reason I tend to use the Regex solution, mainly because it’s very short and simple to implement.
public static bool IsNumeric(string str)
{
return Regex.IsMatch(str, "^[0-9]+$");
}
It also requires the using directive System.Text.RegularExpressions