Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nullcheck before int.TryParse [closed]

Tags:

c#

int

I have code where many strings get parsed into integer values.

string item = null; //or a value
int result;
if (!string.IsNullOrEmpty(item) && int.TryParse(item, out result))
{
    //do stuff
}

Is it really required to check IsNullOrEmpty each time? If it is null or empty, a parse should fail.

like image 761
Toshi Avatar asked Dec 03 '22 23:12

Toshi


1 Answers

No, String.IsNullOrEmpty is redundant here because Int32.TryParse handles that case by returning false. So this is more concise:

int result;
if (int.TryParse(item, out result))
{
    //do stuff
}

MSDN:

The conversion fails if the s parameter is null or String.Empty, is not of the correct format, or represents a number less than MinValue or greater than MaxValue.

like image 147
Tim Schmelter Avatar answered Dec 18 '22 05:12

Tim Schmelter