What is the difference in both of the expressions ? Using brackets or not in this case. What is the difference ?
(!String.IsNullOrEmpty(model.SpouseCitizenType) || !String.IsNullOrEmpty(model.SpouseNomPrenom)) &&
String.IsNullOrEmpty(model.SpouseEGN);
!String.IsNullOrEmpty(model.SpouseCitizenType) || !String.IsNullOrEmpty(model.SpouseNomPrenom) &&
String.IsNullOrEmpty(model.SpouseEGN);
Operator AND && has a higher precendence than OR ||. So, if we denote conditions used here as 1, 2 and 3, first line is equvalent to
(1 || 2) && 3
and the second
1 || (2 && 3)
For the full list of operators sorted in order of precedence check out this MSDN page
Related
This question already has answers here:
C# conditional AND (&&) OR (||) precedence
(6 answers)
Closed 3 years ago.
I'm going through some C# coding exercises and have run into some operator logic that's stumped me.
The following line of code evaluates to false:
int a = 40, int b = 50;
if (a >= 20 && a <= 30 && (b < 20 || b > 30))
{
return a;
}
However, if I remove the brackets from inside the if statement, it evaluates to true.
if (a >= 20 && a <= 30 && b < 20 || b > 30)
{
return a;
}
Can anyone explain what I'm missing? Given that a isn't between 20 and 30, shouldn't it return false? I don't understand why putting the b portion of the if statement in brackets makes it evaluate to false.
Is it evaluating everything prior to "b > 30" as a single condition?
This is all to do with operator precedence.
Just like how * are evaluated first before + (we say * has a higher precedence than +), && is evaluated before ||, as specified.
In the first code snippet, you used brackets to "override" this precedence, making the || part evaluate first, just like how you can add parenthesis to the expression 1 + 2 * 3 to make it evaluate to 9 instead of 7.
a >= 20 && a <= 30 && (b < 20 || b > 30)
^^^^^^^^^^^^^^^^^
this part first
which becomes:
a >= 20 && a <= 30 && true
^^^^^^^ ^^^^^^^
now these parts
which becomes:
false && false && true
resulting in false.
In the second example however, there are no parentheses so the expression is evaluated according to the normal precedence rules:
a >= 20 && a <= 30 && b < 20 || b > 30
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
This part first
Which becomes:
false || b > 30
^^^^^^
then this
which becomes:
false || true
resulting in true.
If you look at the second part where you have removed the parenthesis, it is now divided into two subparts.
First one being : a >= 20 && a <= 30 && b < 20 This evaluates to false.
First one being : b > 30 This statement evaluates to true.
So at the end you have something like this
F || T from both the statements which should eventually give you true as end result
If I have the following C# code:
int i = 1;
bool b = true;
if (i & 1 == 1 && b)
...
I get an error:
operator & cannot be applied to operands of type int and bool
I can do:
if (i & 1 == 1)
and
if (b)
I have tried putting them in brackets:
if ((i & 1 == 1) && b)
if (i & 1 == 1 && (b))
if ((i & 1 == 1) && (b))
but it made no difference.
What am I missing here?
I know I can just put them in separate ifs, but I'm trying to understand what's going on here. Is it a bug?
I'm using VS 2015. Target framework is 4.6.2.
Precedence rules; == is higher than & or &&; so in the left expression (i & 1 == 1) you actually mean: (i & 1) == 1. Then the combined expression is:
if ((i & 1) == 1 && b)
Actually, it is odd that you say this works:
if (i & 1 == 1)
because I get CS0019 "Operator '&' cannot be applied to operands of type 'int' and 'bool'" for that!
I've a bit problem with a short circuit condition, what I need to do is check if an array have almost 2 indexes or a string is equal to a certain value, to recreate the problem here, suppose this:
string[] favItem = new string[] { "hello", "world", "test", "foo" };
string temp = "hello";
var itemToRemove = temp.Split(',');
foreach(var fav in favItem)
{
if(fav == "foo" || (itemToRemove.Length > 1 & fav == itemToRemove[0] || fav == itemToRemove[1]))
{
//do something
}
}
so essentially I need to compare fav with a default value, if this fail, I need to check if the itemToRemove array have almost 2 indexes, if yes I need to compare the fav value in iteration, with the two indexes of itemToRemove.
Now suppose that in itemToRemove there is only one index, I'm not able to exit from this:
(itemToRemove.Length > 1 & fav == itemToRemove[0] || fav == itemToRemove[1])
in particular with & I'm trying to exit from the condition if the indexes aren't two.
In the debug mode I can see the false value with the breakpoint, but I don't understand why the code fall to:
OutOfRangeException
with itemToRemove[1] when should be leave the condition.
What am I doing wrong?
Your code has two problems.
First, the short-circuiting boolean "and" operator is &&. & is the bitwise and operator, and does not short circuit.
Secondly, && has a higher precedence than ||, so you need to group the second || together like this (itemToRemove.Length > 1 && (fav == itemToRemove[0] || fav == itemToRemove[1])). The rule of thumb to remember precedence is that and is like multiplication 0 && 1 = 0, while or is like addition 0 || 1 = 1.
Short circuit is && not &.
I have this Or condition in an IF statement (in a foreach loop) in a Windows Form C# program:
if ((splittedFile.Count() != 3) || (splittedFile.Count() != 4))
continue;
and it always does continue, even if splittedFile.Count() is 3 or 4.
The thing is that if I remove the Or condition:
if ((splittedFile.Count() != 4))
continue;
it works properly!! Any ideas why?
This is the correct behavior, you need to use &&.
The reason is that the count is fixed number, let's say n. Now the condition reads:
n is not 3 or n is not 4.
Given n is 4, this means it is not 3, thus the test succeeds and vice versa.
A compiler can't detect this is trivially true, because between the two if statements, the Count() might change (for instance in a multithreading setting where the second thread would add/remove something to/from the collection). I agree however some analysis tools could be capable in some conditions to detect such trivial behavior. In general however such analysis can't be implemented because of Rice's theorem.
If you use &&, the expression reads:
n is not 3 and n is not 4.
Thus both conditions should be true. In other words only if n is less than three and greater than 4, the condition holds.
Try:
if ((splittedFile.Count() != 3) && (splittedFile.Count() != 4))
continue;
I know || sound logical because : if splittedFile.count is not 3 OR it is not 4 then continue; But because there are 2 NOT ! operators in the if expression an AND && is needed.
put a real number into your expression:
if( 3 != 3 || 3 != 4)
which is
if( false || true )
your expression will always be true, as splittedFile.Count() is always (not 3) or (not 4)
you want to && your results together, which looks like
(x != 3) || (x != 4)
or
!( x == 3 || x == 4)
Because one of your expressions will be always true. That's why true || something always returns true.
Let's analyze your splittedFile.Count() is 3, 4 and other than these values.
For 3, your expression will be false || true and this returns true.
For 4, your expression will be true || false and this returns true.
For other than 3 or 4, your expression will be true || true and this returns true.
Strongly suspect you are looking for && operator which provides logical-AND.
not sure if this make sense at all
im trying to understand how C# process the following logic
false && true || false
false || true && false
basically i'm trying to find out how C# evaluate these expression when there is no parentheses .
&& has a higher precedence than || so it's evaluated first. Effectively, they're equivalent to:
false && true || false => (false && true) || false => false
false || true && false => false || (true && false) => false
If you're unsure, use the parentheses. They have no real negative impact and anything that makes code more readable is generally a good thing.
Perhaps a better example (so that the results are different) would have been:
true && false || false => (true && false) || false => false
true || false && false => true || (false && false) => true
The compiler figures it out because the standard specifies operator precedence.
That said, if an expression requires you to think for more than a second about what is happening in what sequence... use parentheses to make it clear =)
C# Operators shows operator precedence:
false && true || false = (false && true) || false = false
false || true && false = false || (true && false) = false
&& (logical AND) has higher precedence than || (logical OR)
NOTE: it is good practice (some might say best practice) to always use parentheses to group logical expressions, so that the intention is unambiguous...
Everyone said about the operator precedence and the reference tables where you can look that up. But I'd like to give a hint how to remember it. If you think of false as of 0 and of true as of 1 then && is like multiplication and || is like addition (they are actually called logical multiplication and logical addition). The precedence relationship is the same: multiplication is higher then addition. It works the same way:
0 * 0 == 0 | false && false == false
0 * 1 == 0 | false && true == false
1 * 0 == 0 | true && false == false
1 * 1 == 1 | true && true == true
0 + 0 == 0 | false || false == false
0 + 1 == 1 | false || true == true
1 + 0 == 1 | true || false == true
1 + 1 == 1* | true || true == true
(*) it's actually 2 capped at 1
And normally, when in doubt, use parenthesis.
The operators will be evaluated in order of operator precedence.
So, basically, AND before ORs. Your examples are the same as:
(false && true) || false
false || (true && false)
Most importantly... C# uses short circuit operators. So that entire thing is false
link text
operator precedence
short circuit evaluation
parenthesis
left to right.
The the AND operator has higher precedence than the OR operator (see http://msdn.microsoft.com/en-us/library/6a71f45d.aspx). Meaning && is always evaluated first.
Thus x && y || z is understood to be (x && y) || z.
And a || b && c is understood to be a || (b && c).