In the following piece of code, the compiler gives a "Use of unassigned local variable" on 'intValue' on the return line. However, there is no case where "intValue > 500" will be reached where it will be unassigned (because if intValue
is unassigned, then valueIsInt
is false, and the statement returns false before reaching intValue
)
Is there a way to get around this issue without modifying the logic or business logic of the code? This is a very simplified example; in a case where intValue
is another type and the condition intValue > 500
is more complex, we can't simply give intValue a value in the else
block like intValue = 0
bool valueIsInt;
if (value is int intValue)
{
valueIsInt = true;
}
else
{
valueIsInt = false;
}
return valueIsInt && intValue > 500;
I want to avoid this in case the code in the else statement is more complex:
else
{
return false;
}
Such as this:
bool valueIsInt;
if (value is int intValue)
{
valueIsInt = true;
}
else
{
if (value is string stringValue)
valueIsInt = int.TryParse(stringValue, out intValue);
else
return false;
}
return valueIsInt && intValue > 500;