Here’s a quick and dirty implementation of “IsNumeric” in C#. This is one of those methods that just seems to be missing from C# which appears in so many other languages.
UPDATE 12-Apr-2011: After some fantastic discussion elsewhere I’ve modified the code to handle a number of additional scenarios. A point was also raised that a combination of Int64.TryParse() and Decimal.TryParse() would accomplish the same thing. They would, almost, but those methods test for valid 64-bit integers and valid 64-bit decimals — they don’t test whether a string is numeric. Feed them a long enough string of numbers and they’ll return false. It’s a pretty fine distinction, I grant that, but I figured since I was writing the code I might as well make it as robust as possible.
public static bool IsNumeric(string s)
{
return IsNumeric(s, false);
}
public static bool IsNumeric(string s, bool allowDecimal)
{
bool result = true;
if (String.IsNullOrEmpty(s))
{
return false;
}
if (s.StartsWith("-"))
{
s = s.Substring(1);
}
char[] chars = s.ToCharArray();
if (allowDecimal)
{
bool decimalFound = false;
foreach (char c in chars)
{
if (c == '.' && !decimalFound)
{
decimalFound = true;
}
else
{
result = result & (char.IsNumber(c));
}
}
}
else
{
foreach (char c in chars)
{
result = result & char.IsNumber(c);
}
}
return result;
}
I built 14 39 unit tests for this on the project I built it for throwing all sorts of weird and null data at it, and it seems to run fairly well and reasonably quickly. Any comments/suggestions are welcome.








