Search code examples
c#.netwpfcompiler-bug

Why does this code seem to exhibit a bug?


I've got a CanExecute for a WPF command that seems to work differently depending on how explicit I am with the compiler; the problem is, I wouldn't expect to have to be explicit.

private bool CanRemoveField()
{
    return SelectedField != null &&
        Context.Item.Id == 0
        ? _fieldsByFieldModel.ContainsKey(SelectedField)
        : !_hasAnyCosts;
}

The above code, when queried for an Item where Id != 0 holds true, the button is enabled despite SelectedField being null, so I'd expect the conditional to short out and return false.

The code tweaked slightly:

private bool CanRemoveField()
{
    return SelectedField != null &&
        (Context.Item.Id == 0
        ? _fieldsByFieldModel.ContainsKey(SelectedField)
        : !_hasAnyCosts);
}

I've introduced some parentheses around the ternary if, and this now exhibits the desired behaviour of disabling the button when no field is selected.

Given the fact it's a ternary if, I'd have expected the behaviour I wanted to be possible without the need for parentheses as it should just be seen as one statement, no?


Solution

  • The results you're seeing make sense, since the && logical-and operator has a higher precedence than the ? : conditional expression.

    So your first code snippet is essentially:

    return (SelectedField != null && Context.Item.Id == 0)
        ? _fieldsByFieldModel.ContainsKey(SelectedField)
        : !_hasAnyCosts;