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.
No, String.IsNullOrEmpty
is redundant here because Int32.TryParse
handles that case by returning false
. So this is more concise:
if (int.TryParse(item, out int 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.