A C# IsNumeric Function

As much as I love the .NET Framework and C# (and VB.NET too), sometimes I just have to scratch my head and think "Why?" For example, why no InputBox() function in C# (click here for my custom C# InputBox class)? Also, why no IsNumeric() function in C#? VB has had one for years. So, I set out to write my own.

My first inclination was simply to have a function that would attempt to convert a value from either an object or string to a numeric type, wrapped in a try block, and return false if an exception was caught. But as another developer pointed out to me, and as I experienced first hand, when the exception is thrown there is a noticable pause. A much better solution is to use the TryParse() method of the Double class.

The TryParse method attempts to convert a value to a double, but instead of throwing an exception if the conversion fails, it simply returns false. This seems like enough right there, but the function takes an out parameter, so you need at least two lines of code to accomplish the IsNumeric() functionality. Below is my approach:

public bool IsNumeric( string psValue ) {
   Double db;
   return Double.TryParse( psValue,
         System.Globalization.NumberStyles.Any,
         System.Globalization.NumberFormatInfo.InvariantInfo,
         out db );
}

Comments

Popular Posts

Resolving the "n timer(s) still in the queue" Error In Angular Unit Tests

Silent Renew and the "login_required" Error When Using oidc-client

How to Get Norton Security Suite Firewall to Allow Remote Desktop Connections in Windows

Fixing the "Please add a @Pipe/@Directive/@Component annotation" Error In An Angular App After Upgrading to webpack 4

How to Determine if a Column Exists in a DataReader