Archive for August, 2003

IsNumeric

From http://weblogs.asp.net/pgreborio/ by Gregorio
IsNumeric
To test if the string content is a valid integer we can use the VB function IsNumeric. C# doesn’t provides such a function then we have to write our own helper function to do so. One of the most common approach I’ve seen on the newsgroups is the following code:

[code=csharp]public static bool IsNumeric(string inputData)
{
  try
  {
    int.Parse(inputData);
    return true;
  }
  catch
  {
    return false;
  }
}[/code]

If the string isn’t a valid integer I’ll get a FormatException or OverflowException if it is valid but out of the integer domain. Another approach is to use Convert.ToInt32() instead of Parse. From a performance point of view the two solutions are pretty the same.

A very competitive way is to use Regular Expressions checking if the string data contains really only digits:

[code=csharp]private static Regex _isNumber = new Regex(@”^d+$”);

public static bool IsNumeric(string inputData)
{
    Match m = _isNumber.Match(inputData);
    return m.Success;
}[/code]

In this case, the regular expression is compiled once and then the solution is, more or less, 4 times faster than the previous ones.