Search code examples
c#booleanternary-operatorboolean-expressionshort-circuiting

Why does this ternary statement return false positives when in shorthand notation?


I've been scratching my head on this one, since these statements seem almost identical aside from format - however the shorthand one seems to evaluate differently, and creates false positives by returning true when it shouldn't.

In the below examples, imagine programRecord.Award = 'Emmy' and targetAward = 'Oscar'

Bad code giving false positives:

private bool MatchMe(string programId, string targetAward, string targetLevel, Program programRecord)
{
    var isMatched = programRecord.Status == "Active"
        && string.IsNullOrEmpty(programId) ? true : programRecord.Pid == programId
        && string.IsNullOrEmpty(targetAward) ? true : programRecord.Award == targetAward
        && string.IsNullOrEmpty(targetLevel) ? true : programRecord.Level == targetLevel;
    return isMatched;
}

Good code:

    private bool MatchMe(string programId, string targetAward, string targetLevel, Program programRecord)
    {
        var isMatched = programRecord.Status == "Active";
        var isMatched2 = string.IsNullOrEmpty(programId) ? true : programRecord.Pid == programId;
        var isMatched3 = string.IsNullOrEmpty(targetAward) ? true : programRecord.Award == targetAward;
        var isMatched4 = string.IsNullOrEmpty(targetLevel) ? true : programRecord.Level == targetLevel;
        var doIMatch = isMatched && isMatched2 && isMatched3 && isMatched4;
        return doIMatch;
    }

What is occurring in the shorthand version that causes this? I would think the one false value would force the entire statement to return false, however that doesn't occur with the abbreviated version.


Solution

  • As other have shown, you need to surround the ternary expressions in brackets. The reason being is that, && operator has a higher precedence than ?: operator.

    See: 7.2.1 Operator precedence and associativity