I've been using the following small code snippet for years as a pure C# IsNumeric
function.
Granted, it's not exactly the same as the Microsoft.VisualBasic
library's IsNumeric
function as that (if you look at the decompiled code) involves lots of type checking and usage of the IConvertible
interface, however this small function has worked well for me.
Note also that this function uses double.TryParse
rather than int.TryParse
to allow both integer numbers (including long
's) as well as floating point numbers to be parsed. Also note that this function specifically asserts an InvariantCulture
when parsing (for example) floating point numbers, so will correctly identify both 123.00
and 123,00
(note the comma and decimal point separators) as floating point numbers.
using System;
using System.Globalization;
namespace MyNumberFunctions
{
public static class NumberFunctions
{
public static bool IsNumeric(this object expression)
{
if (expression == null)
{
return false;
}
double number;
return Double.TryParse(Convert.ToString(expression, CultureInfo.InvariantCulture), NumberStyles.Any, NumberFormatInfo.InvariantInfo, out number);
}
}
}
Usage is incredibly simple, since this is implemented as an extension method:
string myNumberToParse = "123.00";
bool isThisNumeric = myNumberToParse.IsNumeric();