Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lack of IsNumeric function in C#

One thing that has bothered me about C# since its release was the lack of a generic IsNumeric function. I know it is difficult to generate a one-stop solution to detrmine if a value is numeric.

I have used the following solution in the past, but it is not the best practice because I am generating an exception to determine if the value is IsNumeric:

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

Is this still the best way to approach this problem or is there a more efficient way to determine if a value is numeric in C#?

like image 586
Michael Kniskern Avatar asked May 26 '10 22:05

Michael Kniskern


People also ask

What can I use instead of IsNumeric?

Avoid using the IsNumeric() function, because it can often lead to data type conversion errors, when importing data. On SQL Server 2012 or later, use the Try_Convert() or Try_Cast() function instead. On earlier SQL Server versions, the only way to avoid it is by using LIKE expressions.

What does IsNumeric function do?

Returns a Boolean value indicating whether an expression can be evaluated as a number. The required expressionargument is a Variant containing a numeric expression or string expression. IsNumeric returns True if the entire expression is recognized as a number; otherwise, it returns False.

What is IsNumeric value?

IsNumeric (value) This built-in function returns a value indicating whether or not a variable can be converted to a numeric data type. The argument value can be any string expression. The IsNumeric function returns True if the expression can legally be converted to a number; otherwise, it returns False.

Is numeric function C#?

IsNumeric() function in C#IsNumeric() function returns True if the data type of Expression is Boolean, Byte, Decimal, etc or an Object that contains one of those numeric types, It returns a value indicating whether an expression can be converted to a numeric data type.


1 Answers

Try this:

int temp;
return int.TryParse(input, out temp);

Of course, the behavior will be different from Visual Basic IsNumeric. If you want that behavior, you can add a reference to "Microsoft.VisualBasic" assembly and call the Microsoft.VisualBasic.Information.IsNumeric function directly.

like image 76
mmx Avatar answered Sep 18 '22 21:09

mmx