Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to test if a value is numeric in C#

Tags:

c#

.net

I just need to know if the value is numeric. I don't need to do anything with the value. Is this the best way? Feel dirty creating a variable that I won't ever use beyond this:

int val;
if(int.TryParse(txtFoo.Text, out val))
{
    ....
}
like image 521
Joe Avatar asked Apr 07 '11 16:04

Joe


2 Answers

Yes, using the relevant TryParse method and ignoring the out parameter is the best way of doing this.

You may want to wrap this up into your own set of helper methods (which could specify the appropriate culture etc, if the default isn't right for you) and just return a bool without the out parameter to make them easier to call.

Of course, you need to work out what kind of parsing is most appropriate - even for integers, you need to consider whether the range of Int32 is enough for your use case. In my experience, most numeric input has its own "natural" range of valid values, which is unlikely to be exactly the range of any predefined type. You may therefore want to expand your helper methods to include the range of valid values to accept.

like image 79
Jon Skeet Avatar answered Sep 28 '22 08:09

Jon Skeet


"is numeric" is an ambiguous term.

  • Culture-aware?
  • Allow thousands and/or decimal separators?
  • Allow scientific notation?
  • Allow a sign (before? after?...)
  • What range of values do you allow? Signed 32-bit integer (Int32.TryParse), Unsigned 32-bit integer (UInt32.TryParse), decimal, double, ...

Hence there is no "best" way, and the Framework provides a multitude of different ways to parse numbers.

like image 42
Joe Avatar answered Sep 28 '22 08:09

Joe