C# conditional AND (&&) OR (||) precedence
Solution 1:
Change the first false by true. I know it seems stupid to have (true || true) but it proves your point.
bool result = true || true && false; // --> true
result = (true || true) && false; // --> false
result = true || (true && false); // --> true
Solution 2:
If you really want to freak him out try:
bool result = True() | False() && False();
Console.WriteLine("-----");
Console.WriteLine(result);
static bool True()
{
Console.WriteLine(true);
return true;
}
static bool False()
{
Console.WriteLine(false);
return false;
}
This will print:
True
False
False
-----
False
Edit:
In response to the comment:
In C#, |
is a logical operator that performs the same boolean logic as ||
, but does not short-circuit. Also in C#, the |
operator has a higher precedence than both ||
and &&
.
By printing out the values, you can see that if I used the typical ||
operator, only the first True
would be printed - followed by the result of the expression which would have been True
also.
But because of the higher precedence of |
, the true | false
is evaluated first (resulting in true
) and then that result is &&
ed with false
to yield false
.
I wasn't trying to show the order of evaluation, just the fact that the right half of the |
was evaluated period when it normally wouldn't be :)
Solution 3:
Wouldn't this get you what you're after? Or maybe I'm missing something...
bool result = true || false && false;
Solution 4:
You don't prove it with code but with logic. AND is boolean multiplication whereas OR is boolean addition. Now which one has higher precedence?