Saturday, April 17, 2010

C# equivalent to the VB.NET IsNumeric Function

One of the great function VB.NET makes available to developers is the "InNumeric" function. This function returns a boolean value indicating wheather an expression can be evaluated as number or not. If you lookup the definition of it however, you will see that the function supported in C#.

There are several different ways to code a custom function to do the same in C#. Here is one way:

using System;
using System.Text;
using System.Text.RegularExpressions;

public static bool IsNumeric(string psInputString)
 return Regex.IsMatch(psInputString, "^[0-9]+$");

And here is how Microsoft recommends it on THIS page:

static bool IsNumeric(object Expression)
 bool isNum;
 double retNum;
 isNum = Double.TryParse(
   out retNum );
 return isNum;

Either way you will get the same result.

Pete Soheil
DigiOz Multimedia

No comments: