MSMVPS.COM
The Ultimate Destination for Blogs by Current and Former Microsoft Most Valuable Professionals.

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.


Posted Nov 03 2003, 11:04 AM by ch21st

Add a Comment

(required)  
(optional)
(required)  
Remember Me?


Copyright © is the original authors. Blog site is an independent site not sponsored by Microsoft. The Yoda blog server and the Brianna SQL server would like to thank www.ownwebnow.com and www.exchangedefender.com. They wouldn't be here and broadcasting without the generosity of Vlad Mazek and his companies.

Powered by Community Server (Commercial Edition), by Telligent Systems