Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easier way of checking Int32.TryParse

Tags:

c#

I am seeing lots of these in a method in our code:

int num1 = 0;
if (Char.IsDigit(myStr[2]) && Int32.TryParse(myStr[2].ToString(), out num1) == false)
{
    valid = false;
}

So are they just making sure the third character us a digit?

like image 892
ConfusedSleepyDeveloper Avatar asked Dec 03 '22 18:12

ConfusedSleepyDeveloper


1 Answers

The code shown parses the 3rd character only - checking if it is digit, then parsing the string representation of that single character. Instead, just use the numeric value of that character:

if(myStr[2] >= '0' && myStr[2] <= '9') {
    num1 = (int)myStr[2] - (int)'0';
} else {
    valid = false
}
like image 91
Marc Gravell Avatar answered Dec 15 '22 08:12

Marc Gravell