||(Or) Logical Operator in Java vs .Net [closed] - c#

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.

Related

what is the use of ?? in c# [duplicate]

This question already has answers here:
What do two question marks together mean in C#?
(19 answers)
Closed 5 years ago.
I know ? checks for null when placed before a . member access and ?: for conditional statements. Although, I think ?? checks for null as well but I'm not very sure
I can't find useful information about ?? on https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/
PS. Actually I didn't look well at the MSDN reference very well. I've just seen its definition now.
I though of closing this post before but I won't for the sake of anyone who wouldn't think of referring to ?? as double question marksin their question
that operator is sugarSyntax for operations with nullable operands
The ?? operator returns the left-hand operand if it is not null, or else it returns the right operand.
int? counter = null;
int backup = counter ?? 0;
in this case backup will be assigned with counter value IF counter is different to null, for something ELSE then backup will be assigned with 0
note that I bold the keywords IF-ELSE which make us infer that ?? operand can be replaced by simple old-school if else conditionals.

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.

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.

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

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.

How to use ?: operator [closed]

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 10 years ago.
How would I convert the following code to use the ?: operator.. Is it Possible?
tbtotalamount.Text = string.Format("{0:n2}", dtl.Compute("sum(NetPay)", ""));
if (tbtotalamount.Text.Length == 0)
{
tbtotalamount.Text = "0";
}
The quoted code wouldn't benefit from using the ? : operator, which is called the conditional operator (sometimes called "the ternary operator" although technically, it's only a ternary operator — e.g., an operator that has three operands).
Typically the conditional operator is handy for when you have a variable and want to assign one of two values to it on the basis of a condition. So code in this form:
if (someCondition) {
a = "one value";
}
else {
a = "a different value";
}
can be rewritten
a = someCondition ? "one value" : "a different value";
In your case, though, you don't know that tbtotalamount.Text is blank until after you've done the string.Format, so you're better off leaving it with the if.
Yes. Here's how:
string test = string.Format("{0:n2}", dtl.Compute("sum(NetPay)", ""));
tbttotalamount.Text = test.length == 0 ? "0" : test;
Sorry to see so many downvotes, I'm not familiar with the ? (ternary) operator for a very long time either. I think it is very handy.
To the left of it is your test expression, it should be a boolean after evaluation. To the right is what the operator returns: if true, it will return the value to the left of the :. If false, the value to the right. Note that the whole expression returns something, and the compiler needs you to do something with it. You can't use the ternary operation to replace if-else statements that call functions whose return type is void.
What I mean to say is that a lot of people who've never used it before (like me) seem to think this is a pure if-else replacement, which it is not.

Categories

Resources