We get into unnecessary coding arguments at my work all-the-time. Today I asked if conditional AND (&&) or OR (||) had higher precedence. One of my coworkers insisted that they had the same precedence, I had doubts, so I looked it up.
According to MSDN AND (&&) has higher precedence than OR (||). But, can you prove it to a skeptical coworker?
http://msdn.microsoft.com/en-us/library/aa691323(VS.71).aspx
bool result = false || true && false; // --> false
// is the same result as
bool result = (false || true) && false; // --> false
// even though I know that the first statement is evaluated as
bool result = false || (true && false); // --> false
So my question is how do you prove with code that AND (&&) has a higher precedence that OR (||)? If your answer is it doesn't matter, then why is it built that way in the language?
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
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 :)
Wouldn't this get you what you're after? Or maybe I'm missing something...
bool result = true || false && false;
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?
false || true && true
Yields: true
false && true || true
Yields: true
You cannot just show the end result when your boolean expressions are being short-circuited. Here's a snippet that settles your case.
It relies on implementing & and | operators used by && and ||, as stated in MSDN 7.11 Conditional logical operators
public static void Test()
{
B t = new B(true);
B f = new B(false);
B result = f || t && f;
Console.WriteLine("-----");
Console.WriteLine(result);
}
public class B {
bool val;
public B(bool val) { this.val = val; }
public static bool operator true(B b) { return b.val; }
public static bool operator false(B b) { return !b.val; }
public static B operator &(B lhs, B rhs) {
Console.WriteLine(lhs.ToString() + " & " + rhs.ToString());
return new B(lhs.val & rhs.val);
}
public static B operator |(B lhs, B rhs) {
Console.WriteLine(lhs.ToString() + " | " + rhs.ToString());
return new B(lhs.val | rhs.val);
}
public override string ToString() {
return val.ToString();
}
}
The output should show that && is evaluated first before ||.
True & False
False | False
-----
False
For extra fun, try it with result = t || t && f and see what happens with short-circuiting.
Related
I have several booleans I need to check and turn into a single boolean for readability:
bool myBoolean = 5 == 5 && "string" == "String" && true && false && CheckSomethingElse();
Is there a way I can break this up into multiple lines to make it more readable? I can do this:
bool myBoolean = 5 == 5;
myBoolean = myBoolean && "string" == "String";
myBoolean = myBoolean && true;
myBoolean = myBoolean && false;
myBoolean = myBoolean && CheckSomethingElse();
But I am looking for something more along the lines of this:
bool myBoolean = 5 == 5;
myBoolean &= "string" == "String";
myBoolean &= true;
myBoolean &= false;
myBoolean &= CheckSomethingElse();
However, the third code block does not do the same thing as the first/second (as far as I know). Does C# have a way to improve the readability from the first code block? Or is there some sort of a normal way to code such a boolean?
For readability, simply extract it out into a named method where the name of the method instantly tells you the intent:
public bool FluxCapacitorIsReady()
{
return 5 == 5
&& "string" == "String"
&& true
&& false
&& CheckSomethingElse();
}
Now you can just call that method in your code and it is immediately clear to any reader what is going on:
if (FluxCapacitorIsReady())
StartFluxCapacitor();
This is a concept from Clean Code: see http://cleancoders.com for more.
First, I may agree with some of JK and etc. opinions about rewriting, but to actually answer your question according to SO guidelines, The correct answer is No because that operator is not defined in C# and you can not overload a new operator like that for the Boolean type.
I think the best you can get is defining an extension method for the Boolean type
public static class BoolExtension{
public static bool And(this Boolean first, bool second){
first = first && second;
return first;
}
public static bool MultiAnd(this Boolean first, params bool[] others)
{
foreach (var b in others) first = first && b;
return first;
}
}
and then use it like this
bool myBoolean = 5 == 5;
myBoolean.And( "string" == "String");
myBoolean.MultiAnd("A"=="A","B"=="C","D"=="D");
As you can see, this may not help much with readability.
Some people end up implementing a Decorator pattern for the Boolean class in such cases by defining a struct/class that has a Boolean inside it and does operator overloading that you like.
My question is why this condition in a for loop makes it cancel out iteration, however it seems to me that condition is fulfilled?! If I try with one of two given variables without using AND operator looping works and continues infinitely.
bool a = false;
bool b = false;
for (; a && b == false; )
{
Console.WriteLine("");
}
This condition
a && b == false
means
a && (b == false)
Since && does short circuit evaluation, the first false will result in false for whole expression, and thus there is no need to evaluate second expression.
Also to add, even with a single & (which doesn't perform short circuit evaluation, your complete condition will result in false.
If you want to compare both a and b to false you can do:
a == false && b == false
or
!a && !b
You should also consider using a while loop, if there is no iteration variable involved.
https://msdn.microsoft.com/en-us/library/aa691323%28v=vs.71%29.aspx
Because the == is evaluated before &&, the condition is a && (b == false)
so false.
I have two lists of Enums and I want to perform And kind of operation between them. Let suppose my enum definition has 3 elements true, false and NA.
public enum myEnum {
True,
False,
NA
}
I have two lists List1 and List2 and both contain 10 elements. I want these results:
True && False = False
True && NA = NA
False && NA = False
True && True = True
False && False = False
NA && NA = NA
I want to know to that is there any built-in functionality in C# which can give me results which I mentioned above. I am trying to avoid writinig long code.
Start out writing the method that can perform the And operation that you want on just two values, using the logic that you described. This is actually handled quite easily, as if either value is False you return False, if none is False and one is NA you return NA, and if both are true you return true, the only remaining case.
public static myEnum And(this myEnum first, myEnum second)
{
if (first == myEnum.False || second == myEnum.False)
return myEnum.False;
if (first == myEnum.NA || second == myEnum.NA)
return myEnum.NA;
return myEnum.True;
}
Next, it appears that you want to compare the item from each list that is at the same index, so the first is compared to the first, the second to the second, etc., to create a new list of the same size as the other two. You can use Zip, to perform this logical operation using the method we've already defined:
var query = list1.Zip(list2, (a,b) => a.And(b));
A bool? (Nullable<bool>) has three values and gives you all of the values you expect if you use the logical and (&) operator:
(bool?)true & (bool?)false = false
(bool?)true & (bool?)null = null
(bool?)false & (bool?)null = false
(bool?)true & (bool?)true = true
(bool?)false & (bool?)false = false
(bool?)null & (bool?)null = null
// Example bool is true
bool t = true;
// Convert bool to int
int i = t ? 1 : 0;
Console.WriteLine(i); // 1
This converts false to 0 and true to 1, can someone explain to me how the t ? 1 : 0 works?
Look at the Ternary Operator.
int i = t ? 1 : 0;
Equates to:
if(t)
{
i = 1;
}
else
{
i = 0;
}
This syntax can be found in a variety of languages, even javascript.
Think of it like an English sentence if you swap the colon for "otherwise":
bool isItRaining = false;
int layersOfClothing = isItRaining? 2 otherwise 1;
It's the C# Conditional Operator.
i = does t == true? if yes, then assign 1, otherwise assign 0.
Can also be written as:
if (t == true)
t = 1;
else
t = 0;
or
if (t)
t = 1;
else
t = 0;
Since t is true, it prints 1.
if t equels true then i=1 else i=0
ternary operator
bool t= true;
int i;
if(t)
{
i=1;
}
else
{
i=0;
}
For more look ?: Operator
(? *) this is conditional operator.
The conditional operator (?:) returns one of two values depending on the value of a Boolean expression. The conditional operator is of the form
condition ? first_expression : second_expression;
here in you case (true?1:0 ) since the condition is true ,which is certainly setting value of i to 1.
I believe that internally the compiler will inline the statement to the equivalent of:
Console.WriteLine(Convert.ToInt32(t));
This Convert.x method checks to see if the passed parameter is true return 0 if it isn't.
What does result.IsVisible equal?
if(a==b)
result.IsVisible = obj1.status.abc_REPORT == 'Y'
&& obj1.AnotherValue.ToBoolean() == false;
That depends on the values of obj1.status.abc_Report and obj1.AnotherValue.ToBoolean() (and it all depends on whether a==b or not).
I'm not quite sure of what the real question is here - which bit is confusing you?
One bit which may be confusing you is the shortcircuiting && operator (and possibly the lack of bracing!)
The && operator will only evaluate its right hand side if the left hand side evaluates to true: and the overall result of the expression is true if and only if both sides evaluates to true. (I'm assuming no strange user-defined conversions here.)
So another way of writing it would be:
if (a == b)
{
bool visibility = false;
if (obj1.status.abc_REPORT == 'Y')
{
if (obj1.AnotherValue.ToBoolean() == false)
{
visibility = true;
}
}
result.IsVisible = visibility;
}
Note that a condition comparing Booleans, like this:
obj1.AnotherValue.ToBoolean() == false
would usually be written like this:
!obj1.AnotherValue.ToBoolean()
(Note the exclamation mark at the start - the logical "not" operator.)
The same as this, in many less lines:
if (a==b) {
if (obj1.status.abc_REPORT == 'Y') {
if (obj1.AnotherValue.ToBoolean() == false) {
result.IsVisible = true;
}
else {
result.IsVisible = false;
}
}
else {
result.IsVisible = false;
}
}
In simple words:
If a is equal to b:
result will be visible only if:
object1's status's abc_report is Yes(Y = Yes most probably) AND object1's other value cannot be converted to a Boolean
I'm guess result.IsVisible is a boolean
It will be true if the following conditions are true:
obj1.status.abc_REPORT == 'Y'
and
obj1.AnotherValue.ToBoolean() == false
Also, a == b must be true to enter the initial if
lets go line by line:
if(a==b)
obvious if value of a equals value of b the execute following line
result.IsVisible = obj1.status.abc_REPORT == 'Y'
&& obj1.AnotherValue.ToBoolean() == false;
result is some object (maybe winforms controls etc) which has a property IsVisible set it to true if obj1.status.abc_REPORT is equal to 'Y' and also obj1.AnotherValue.ToBoolean() is equal to false;