简体   繁体   中英

How to get around use of unassigned variable that can never happen?

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;

Updated

static bool IsValueGreaterThan500(object value)
{
    try
    {
        // Converts the value to int if it is not already an int
        // from bool, short, float, double, string, etc.
        return Convert.ToInt32(value) > 500;
    }
    catch
    {
        return false;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM