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#?
Another option - LINQ!
Note that this assumes you only want digits 0-9. If you want to accept decimal point, sign, exponent, etc, then repalce
IsDigit()
withIsNumber()
.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'sIsNumeric
function as that (if you look at the decompiled code) involves lots of type checking and usage of theIConvertible
interface, however this small function has worked well for me.Note also that this function uses
double.TryParse
rather thanint.TryParse
to allow both integer numbers (includinglong
's) as well as floating point numbers to be parsed. Also note that this function specifically asserts anInvariantCulture
when parsing (for example) floating point numbers, so will correctly identify both123.00
and123,00
(note the comma and decimal point separators) as floating point numbers.Usage is incredibly simple, since this is implemented as an extension method:
You can still use the Visual Basic function in C#. The only thing you have to do is just follow my instructions shown below:
Then import it in your class as shown below:
using Microsoft.VisualBasic;
Next use it wherever you want as shown below:
Hope, this helps and good luck!
Try this:
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 theMicrosoft.VisualBasic.Information.IsNumeric
function directly.If you use
Int32.TryParse
then you don't need to wrap the call in a TryCatch block, but otherwise, yes that is the approach to take.Not exactly crazy about this approach, but you can just call the vb.net isNumeric function from C# by adding a reference to the Microsoft.VisualBasic.dll library...
The other approaches given are superior, but wanted to add this for the sake of completeness.