Shannon Shang-I think therefore I am

We came here, you and I, to this place and this profession, to be great, to do great things, and give form to great dreams - and we have

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:

public static bool IsNumeric(string inputData)
{
  try
  {
    int.Parse(inputData);
    return true;
  }
  catch
  {
    return false;
  }
}


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:

private static Regex _isNumber = new Regex(@"^\d+$");

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


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

Leave a Comment

(required) 

(required) 

(optional)

(required)