2

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?

Clint
  • 6,133
  • 2
  • 27
  • 48

2 Answers2

8

Because of operator precedence, your first example is equivalent to:

private bool CanRemoveField()
  {
    return (SelectedField != null &&
        Context.Item.Id == 0)
        ? _fieldsByFieldModel.ContainsKey(SelectedField)
        : !_hasAnyCosts;
  }
Polyfun
  • 9,479
  • 4
  • 31
  • 39
5

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;
Grant Winney
  • 65,241
  • 13
  • 115
  • 165
  • 1
    Thanks! Operator precedence makes sense, I guess I just assumed it would treat the ternary if as a group. – Clint Apr 20 '15 at 10:59