In C#, how to check whether a string contains an integer?

Marcel picture Marcel · Aug 15, 2013 · Viewed 129.5k times · Source

I just want to know, whether a String variable contains a parsable positive integer value. I do NOT want to parse the value right now.

Currently I am doing:

int parsedId;
if (
    (String.IsNullOrEmpty(myStringVariable) ||
    (!uint.TryParse(myStringVariable, out parsedId))
)
{//..show error message}

This is ugly - How to be more concise?

Note: I know about extension methods, but I wonder if there is something built-in.

Answer

DGibbs picture DGibbs · Aug 15, 2013

You could use char.IsDigit:

     bool isIntString = "your string".All(char.IsDigit)

Will return true if the string is a number

    bool containsInt = "your string".Any(char.IsDigit)

Will return true if the string contains a digit