How does C# evaluates AND OR expression with no brackets - c#

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).

Related

how to get 2 false Boolean and return true as result

In math, we have -1 * -1 = 1. When 2 negatives multiplies together, we get a positive.
However in C# bool, I am not able to find a way to do so.
int i = -1
int j = -1
bool bi = i>0
bool bj = j>0
Console.writeLine (bi)
Console.writeLine (bj)
Console.writeLine (bi && bj)
result:
false
false
false
obviously, the && is the not the right operator.
Which operator allows me to have 2 Boolean when both are false, returning true
i.e.
Console.Writeline (false false)
result true
The closest to your logic is using negated XOR:
! (bi ^ bj);
This way you'd get something like:
1 * 1 = 1
-1 * 1 = -1
1 * -1 = -1
Also you could use simple comparison operator ==:
bi == bj;
Which operator allows me to have 2 Boolean when both are false,
returning true
If you want to check two values are equal (e.g. both are true or both are false) then == (the equality operator) is your best bet.
var bob = true == true;
var bob2 = false == false;
Both bob and bob2 will be true.
This is perfect for your problem since you want to know if both numbers are negative or both numbers are positive (since in either of those scenarios, multiplying them will result in a positive number).
Console.Writeline(bi == false && bj == false) or for short (!bi && !bj)

Is null negative or positive?

I know the n.HasValue && n.Value > 0 but really curious to test null value, so:
decimal? n = null;
Console.Write(n>0); // false
Console.Write(n<0); // false
So is null object positive or negative in C# ?
n > 0 compiles to n.HasValue && n.Value > 0, which produces false because n.HasValue returns false. Same for any other condtion, because HasValue always comes first.

C# Conditioning Difference In OR Operator

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

Or in IF statement not working properly

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.

Evaluate condition irrespective of first outcome

I know this is probably a newbie question, however I need to get a recommendation for the design of this.
I need to evaluate the result of a set of conditions and they must be evaluated irrespective of the outcome of a preceding condition. This brings the case of using regular OR(|) or short-circuit evaluation using ||.
Below is the code that I need to make a design decision about, however the end goal is to be able to evaluate or condition regardless.
private bool checkExistingBPNInSession()
{
var exDirectors = (List<ViewModels.NewContact>)Session["NewDirectorDetails"];
var exTaxConsultant=(List<ViewModels.NewContact>)Session[Resources.Global.NewTaxConsultantDetails];
var exTaRep = (List<ViewModels.NewContact>)Session["NewTaxRepresentativeDetails"];
if (exDirectors.Count() != 0 || exTaRep.Count() != 0 || exTaxConsultant.Count() != 0)
{
var QueryCheckDir = (from x in exDirectors where x.BPN==txtBusinessPartnerIdNumber.Text select x.BPN).ToList();
var QueryCheckTaxConsultant = (from x in exTaxConsultant where x.BPN == txtBusinessPartnerIdNumber.Text select x.BPN).ToList();
var QueryCheckTaxRep = (from x in exTaRep where x.BPN == txtBusinessPartnerIdNumber.Text select x.BPN).ToList();
if (QueryCheckDir.Count() > 0 || QueryCheckTaxConsultant.Count() > 0 || QueryCheckTaxRep.Count() > 0)
{
return true;
}
else
{
return false;
}
}
return false;
}
These parts here have to be evaluated:
exDirectors.Count() != 0 || exTaRep.Count() != 0 || exTaxConsultant.Count() != 0
and this also
QueryCheckDir.Count() > 0 || QueryCheckTaxConsultant.Count() > 0 || QueryCheckTaxRep.Count() > 0
Please, I am seeking the best recommendations.
Thanks guys.
If you want an evaluation done, no matter what, you should use the
|-operator - this will evaluate every condition even if the outcome of the final expression would not change (contrary to ||-operator)
Here is a simple demo using dotnetfiddle

Categories