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#?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With