HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpCritical

Identify if a string is a number

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
stringidentifynumber

Problem

If I have these strings:

-
"abc" = false

-
"123" = true

-
"ab2" = false

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

Solution

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!

Code Snippets

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

Context

Stack Overflow Q#894263, score: 1556

Revisions (0)

No revisions yet.