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.
Related
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.
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.
What is the correct way to do something like this.
db.Tasks.Where(t => {t.CategoryId == 1 || t.CategoryId == 2) || t.CategoryId == 3)}).ToList();
Your brackets are just wrong at the moment, both in terms of curly braces and plain parentheses. You don't actually need any brackets within the expression - this is fine (reformatted for clarity):
var list = db.Tasks
.Where(t => t.CategoryId == 1 ||
t.CategoryId == 2 ||
t.CategoryId == 3)
.ToList();
A lambda expression is exactly that – it consists of a single ordinary expression. (such as a || b || c)
Braces are for statements, not expressions.
Just remove the {} and that will work fine.
You also have some stray ).
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
This question applies to every programming language that has a short-circuit AND operator, not just C#.
The question is simple - is using short circuit evaluation to avoid an out of range index exception, for example:
if ((x > 0) && (bar[x] == foo))
or
if (((x > 0) && (x < bar.Length)) && (bar[x] == foo))
bad coding style? I know I could nest the loops like this:
if (x > 0)
{
if (bar[x] == foo)
{
}
}
but I find it to be extremely unreadable.
I would say that
if ((x > 0) && (bar[x] == foo))
is not bad coding style. It's probably even good. I would definitely prefer it to a nested if structure like you describe.
As an aside, I would reduce the number of parentheses you use. Both these are equally correct, at least in C# and most other C-derived languages:
if (x > 0 && bar[x] == foo)
if (x > 0 && x < bar.Length && bar[x] == foo)
Readers who know the language (you have to assume this at some level) will easily be able to understand the above short-circuit expressions. Those readers would probably object to the nested if style, because it takes way more room than is necessary to get the correct behaviour.
I would argue that it can be made a lot cleaner by moving it into its own method:
bool IsXBarValid(int x, Bar bar)
{
return (x > 0) && (bar[x] == foo);
}
// .. then ..
if (IsXBarValid(x, bar))
{
// etc..
}
Obviously I'm not sure how you're implementing it so the method name is a bit whiffy, but generally this is a nice way to clean this sort of code up.
"Bad coding style" (in this case at least) is what you define it to be. Both are perfectly valid and it's just a matter of taste. It also depends on the number of operations you have in the actual if() statement. If there are a lot of comparisons like
if ((foo == bar) && (foobar == something) && ((a==b) || (c==d)))
it might be beneficial to wrap it in a method like:
if (AllMyConditionsAreMet(OnSomeObject))
for easier reading/understanding of what is going on.
I like simon-whitehead's answer best so far.
If I don't want another method I do:
bool foobar = (x > 0) && (bar[x] == foo);
if (foobar)
// etc...
I find these styles a lot more readable than either suggestion in the original post.
It helps others who are reading code (porters or not).
They read foobar, and instantly can decide whether this is the part of code they need to inspect in detail, or whether they can skim on.
If on the other hand they see a complicated if statement, potentially with language trickiness inside :-), then it slows them down.
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 11 years ago.
I have a simple bit of logic.
int i = 0;
if (i < 0) {
//whatever;
}
When I debug with VS I see i set to 0 BUT the if evaluates as false! How can this be?
GUYS. Perhaps I could have worded it better!!! The above expression SHOULD evaluate as false when i is 0 which I see when I hover over it in VS BUT it goes into the brackets and does "whatever"... WHICH is not right.
EDIT: Please see my similarly named but more recent question for a solution.
0 is not less than 0. Its equal to. Do if (i <= 0)
That's because 0 < 0 is false.
Because i is not less than zero. So, the expression evaluates as false, which is correct.
0 is NOT less than 0. it is less than OR EQUAL to 0
It evaluates to false because 0 is not less than 0.
The answer is because i isn't less than 0.
In order for the if statement to evaluate to true, i would need to be a negative integer.
If i equals 0, then it is false, because it is not less than 0.
What you are thinking of is if(i == 0) or if (i <= 0) (or for that matter if(i >= 0)). Each of these are true if i equals 0.
0 < 0 will always be false. Under what condition do you expect it to evaluate to true?
0 < 0 is false. use <= if you want it to evaluate to true if i is 0
Maybe your simple bit of logic needs to be:
int i = 0;
if(i <= 0) {Whatever }
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 12 years ago.
I have been coding in Java(Mainly) and .Net for a while.
What I found is that the || logical operator in .Net is different in result to the || operator in Java.
Lets look at the following Java code:
Object obj = null;
if(obj == null || obj.toString().isEmpty()){
System.out.println("Object is null");
}
The result of the code above will be:
Object is null
The reason for that is because obj == null is true and the second expression wasn't evaluated. If it was, I would have received a java.lang.NullPointerException.
And if I used the single or (|) I would also received a NullPointerException (Both are evaluated).
My question is the following:
If the code was C#, I will always get a ObjectReferenceNotSet etc. exception because the obj value is null and the second expression is always evaluated (Regardless of the operator), meaning the result is different in C# than in Java.
If I would to change the C# code to work properly, I have to create two if statements.
Is there not an easier way to do this in C# to be similar to Java? (Keep it in one if with 2 expressions)
Thank you.
The || operator in C# is short-circuiting, just like in Java. As is &&. The | and & operators are not short-circuiting, just like in Java.
If your results are different, there is a bug in the code. Can you show us the offending C# please?
This works fine:
object obj = null;
if(obj == null || string.IsNullOrEmpty(obj.ToString())) {
Console.WriteLine("Object is null");
}
The || operator has exactly the same meaning in Java and C#. It is called a conditional logical OR, or "short-circuiting" logical OR operator:
http://msdn.microsoft.com/en-us/library/6373h346%28VS.71%29.aspx
This behaviour is a strict java language feature:
At run time, the left-hand operand
expression is evaluated first ;[...] if the resulting value is
true, the value of the conditional-or
expression is true and the right-hand
operand expression is not evaluated.
If the value of the left-hand operand
is false, then the right-hand
expression is evaluated; [...] the
resulting value becomes the value of
the conditional-or expression.
Thus, || computes the same result as |
on boolean or Boolean operands. It
differs only in that the right-hand
operand expression is evaluated
conditionally rather than always
Similar rules are defined for the java conditional-and operator.
Compare (identical) to C#:
The && and || operators are called
the conditional logical operators.
They are also called the
“short-circuiting” logical operators.
conditional-and-expression:
inclusive-or-expression
conditional-and-expression && inclusive-or-expression
conditional-or-expression:
conditional-and-expression
conditional-or-expression || conditional-and-expression
The && and || operators are conditional versions
of the & and | operators:
The operation x && y corresponds to the
operation x & y, except that y is
evaluated only if x is not false.
The operation x || y corresponds to
the operation x | y, except that y is
evaluated only if x is not true.
It's called "short circuit evaluation". There is no need to evaluate the next statement. This is a nice feature in Java.