AND/OR (&&/||) logic for multiple condition statements [closed] - c#

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
If you have an if-statement in C# that checks multiple conditions:
if (a == 5 && b == 9) { ... }
Does b == 9 still get checked if a == 5 condition is false, or does it automatically exit since there's no way this could pass anymore?
Similarly, for an OR if-statement:
if (a == 5 || b == 9) { ... }
Will b == 9 still get checked if a == 5 is true?

Both && and || is "short-circuiting" operators, which means that if the answer is known from the left operand, the right operand is not evaluated.
This means that:
a && b
b will not be evaluated if a is false, since the final answer is already known.
Likewise:
a || b
b will not be evaluated if a is true, since the final answer is already known.
If you want both operands to be evaluated, use the & and | operators instead.
The bonus of this is that you can write expressions that would fail if all operands was evaluated. Here's a typical if-statement:
if (a != null && a.SomeProperty != null && a.SomeProperty.Inner != null)
... use a.SomeProperty.Inner
If a was null, and the expression would go on to evaluate a.SomeProperty, it would throw a NullReferenceException, but since && short-circuits, if a is null, the expression will not evaluate the rest and thus not throw the exception.
Obviously, if you replace && with &, it will throw that exception if either a or a.SomeProperty is null.

Conceptually, && and || short-circuit.
But since you don't have any side-effects there, the JIT compiler is free to remove the short-circuiting. I don't know whether it actually does so or not.

For : if (a == 5 && b == 9) { ... }
Does b == 9 still get checked if a == 5 condition is false, or does it
automatically exit since there's no way this could pass anymore?
If a == 5 is false no any other control will be executed on that line.
For: if (a == 5 || b == 9) { ... }
Will b == 9 still get checked if a == 5 is true?
Pass inside immediately, as first condition already satisfies requirements.

Using the AND operator, according to the boolean logic, all the conditions must be evaluated to TRUE. If only one of them isn't satisfied, the result of the conditions will be FALSE.
Does b == 9 still get checked if a == 5 condition is false, or does it
automatically exit since there's no way this could pass anymore?
It does automatically exit, because the first condition is false and the result is already known.
For the OR operator, you need that, at least, one of the conditions is TRUE and your logic will be executed. If the first one is not satisfied, the application will check the other conditions.
Will b == 9 still get checked if a == 5 is true?
No, it won't be checked, because the first condition is TRUE and then it's not necessary to check another condition.

Short-cirtuiting is defined by standard. Otherwise it would be impossible to say what is the outcome of expression such as:
if (a != null && a.IsValid) { ... }
In some C# compilers it would work fine, in some others it would cause an exception. That's why the standard is there to define common behavior.
EDIT: clarified last statement.

in AND check
a==5
if is true then
will go to b==9 else
will not go to b==9.
in OR:
it will check a==5 and b==9.

Related

Return true if only 1 parameter out of 3 is true [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have 3 arrays and I would like to pass an if statement if only 1 of the 3 arrays are not empty. I only want to pass it if only 1 is not empty and the other 2 are empty.
Right now I have a crazy if statement and was wondering if it can be simplified
if((a && !b && !c) || (!a && b && !c) || (!a && !b && c))
Assuming a, b, and c are boolean values whose values indicate if the corresponding array is empty or not:
(a ^ b ^ c) && !(a && b && c)
If you XOR three boolean values in sequence, it will be true if and only if exactly one variable is true OR if all three variables are true. Hence, the second part of the expression, to eliminate the case where all three variables are true.

In if statement, if one of the parts separated by or returns true, will it continue the statement? [duplicate]

This question already has answers here:
AND/OR (&&/||) logic for multiple condition statements [closed]
(6 answers)
Closed 6 years ago.
If I have an if statement separated by || returns true, will it continue the statement?
for example: if(true || random()), will random() be executed? because there is no reason for that.
random() will not be executed:
The conditional-OR operator (||) performs a logical-OR of its bool operands. If the first operand evaluates to true, the second operand isn't evaluated. If the first operand evaluates to false, the second operator determines whether the OR expression as a whole evaluates to true or false.
See || Operator (C# Reference) and this answer.
No, random() will not be executed if you put || and your first condition is true.
However, with | both conditions get checked no matter what the first result is.

.Net Syntax - what does "=>" do when filtering text within a collection? [duplicate]

This question already has answers here:
What does '=>' do in C#? [duplicate]
(5 answers)
Closed 8 years ago.
Say I have a collection that I want to filter on...
var users = groupInner.GetMembers(true).Where(user => user.Name.ToUpper().StartsWith("D0") == false &&
user.Name.ToUpper().StartsWith("D1") == false &&
user.Name.ToUpper().StartsWith("D2") == false &&
user.Name.ToUpper().StartsWith("D3") == false &&
user.Name.ToUpper().StartsWith("D4") == false).ToList();
When filtering with the where clause on text, I can only get the statement to work with =>. == doesn't seem to work. I've tested it, the above code gives me my correct answer, but just for understanding and to find out if I should using something more appropriate than what I already have...what does => mean when comparing text and is there something I should be using instead?
That's the syntax for indicating a lambda expression. It's called the "lambda operator". See:
http://msdn.microsoft.com/en-us/library/bb397687.aspx
To create a lambda expression, you specify input parameters (if any) on the left side of the lambda operator =>, and you put the expression or statement block on the other side.

How are "anded" 'if' conditions evaluated? [duplicate]

This question already has answers here:
Difference between | and || or & and && for comparison [duplicate]
(7 answers)
Closed 8 years ago.
In C#, if we have the following code:
if (condition1 && condition2)
and condition1 turns out to be false, is condition2 still checked or does the execution simply continue after the if statement?
Firstly it evaluates condition1, then if it is true then it will evaluates condition2. It will not evaluate condition2 if condition1 is false. This is called short-circuit evaluation.
No the && operator is short circuiting. The & operator is however not and all of the expressions will be evaluated if you use that.
Yes C# does short circuit evaluation of boolean expressions. Therefore
if ( X && Y() )
1) X will be executed first
2) Y will only be executed if and only if X returns true
This applies to all boolean expressions and not just those in an IF statement...Check this in the C# Specification available online at MSDN. section 14.11.1
you can use also the & and in this case it won't be a short circuite evaluation because
& is the "and" operator used for bit manipulation.
&& is the "and" operator used to evaluate logically expressions.

Short circuiting not working [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
It was my understanding that C# conditional operators perform short circuiting. However, my program throws an exception while running this code. Index is equal to -1, so the second condition should never execute, but I get an index out of bounds exception.
if (index != -1 || pieces[index].Type != PieceType.Rook)
{
allowed = false;
}
You have used || so when the first condition fails (index IS -1) the runtime needs to check the second condition before excluding the code from execution and that will trigger the exception,
Instead, you use && (AND) if you want to enter the if only when the two conditions are true.
In this way, as before, the runtime checks the first condition and now getting the false result is enough to decide that there is no need to check the second condition..
if (index != -1 && pieces[index].Type != PieceType.Rook)
{
allowed = false;
}
Replace || with &&
if (index != -1 && pieces[index].Type != PieceType.Rook)
Otherwise the second codition is evaluated if the first is false what you don't want. You want both conditions being true and especially the first one.
That's because you use OR operator. First condition is false, so second starts evaluating.
You should have index != 1 && ....
Also, is index < -1 or >= pieces.Length?
|| will stop evaluating when it finds that something is true. Since index != -1 is false it will evaluate both sides of the expression. If you && it would stop once it finds a false. I would recommend reading up on lazy evulation.

Categories

Resources