c# List.Exists returns true with "false && true"

688 views Asked by At

So I was working on a Program and was a little bit confused about the behavior of a Listoperator. I have a List and wanted to know if it holds an entry according to some criterias. Now let's call it a List and obj has the following Properties:

public string PropA { get; set; }
public string PropB { get; set; }
public string PropC { get; set; }
public bool HasPropC { get; set; }

Now I only wanted a true result if PropA was equal to one in the list and if the property in the List has as PropC it should check PropC, otherwise PropB. I used this piece of code for it:

 if (List.Exists(x => {
       bool b = true;

       b = b && x.PropA.Equals(obj.PropA);
       b = b && x.HasPropC ? x.PropC.Equals(obj.PropC) : x.PropB.Equals(obj.PropB);

       return b;
}))

After the first line with the "PropA.Equals..." b was set to false. But the line beyond made it true again. So it seemed like there was an Object even it was not. I found a solution for it, I wrapped the second Line after the &&-Operator into brackets but I still don't know why it made out of a false a true.

Can you give me a hint on this one?

Thanks.

1

There are 1 answers

1
matanso On

In the expression

b && x.HasPropC ? x.PropC.Equals(obj.PropC) : x.PropB.Equals(obj.PropB);

The && operator has precedence over the ?: operator. So, when you evaluated it, b && x.HasPropC has been evaluated to false, and b was assigned with the value x.PropB.Equals(obj.PropB).