Lack of IsNumeric function in C#

2020-07-03 07:48发布

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#?

13条回答
Fickle 薄情
2楼-- · 2020-07-03 08:54

I've used the following extension method before, if it helps at all:

public static int? AsNumeric(this string source)
{
  int result;
  return Int32.TryParse(source, out result) ? result : (int?)null;
}

Then you can use .HasValue for the bool you have now, or .Value for the value, but convert just once...just throwing it out there, not sure what situation you're using it for afterwards.

查看更多
登录 后发表回答