Identify if a string is a number

Gold picture Gold · May 21, 2009 · Viewed 1.1M times · Source

If I have these strings:

  1. "abc" = false

  2. "123" = true

  3. "ab2" = false

Is there a command, like IsNumeric() or something else, that can identify if a string is a valid number?

Answer

mqp picture mqp · May 21, 2009
int n;
bool isNumeric = int.TryParse("123", out n);

Update As of C# 7:

var isNumeric = int.TryParse("123", out int n);

or if you don't need the number you can discard the out parameter

var isNumeric = int.TryParse("123", out _);

The var s can be replaced by their respective types!