Reputation: 12014
I have been looking for an explanation for the order in which boolean expressions are evaluated but cannot find one.
Take a look at this statement :
if (locClsTanken.PlaceID == -1 && locRwF.PlaceID > -1 || locClsTanken.DagPrijs == 0)
How is this evaluated.
will it be like this :
if ((locClsTanken.PlaceID == -1 && locRwF.PlaceID > -1) || locClsTanken.DagPrijs == 0)
or like this :
if (locClsTanken.PlaceID == -1 && (locRwF.PlaceID > -1 || locClsTanken.DagPrijs == 0))
Is there some documentation about this I dont know the correct search term because english is not my language.
I know I can test it but I would like to find the documentation about this so I can fully understand it
Upvotes: 1
Views: 1873
Reputation: 234715
&&
has higher precedence than ||
, so
locClsTanken.PlaceID == -1 && locRwF.PlaceID > -1 || locClsTanken.DagPrijs == 0
is evaluated as
(locClsTanken.PlaceID == -1 && locRwF.PlaceID > -1) || locClsTanken.DagPrijs == 0
Note that &&
and ||
are also short-circuited so evaluation of the right-hand operand only occurs if that could change the result following the evaluation of the left-hand one.
Reference: https://msdn.microsoft.com/en-gb/library/aa691323(v=vs.71).aspx
Upvotes: 5
Reputation: 4183
In C# the compiler moves from left to right, meaning it will evaluate the left most expression first (in your case that is locClsTanken.PlaceID == -1
)
Also, &&
has higher priority than ||
--> gets evaluated first
However, what might confuse you is how the compiler handels the &&
and ||
. There is a difference between &
and &&
.
&
means both expressions have to be true and both expressions are evaluated. However, &&
only causes one expression to be evaluated first. If the first expression fails, then the second one isn't even evaluated, because in order for &&
to be true both expressions need to be true. If the first one already fails &&
is always false --> &&
is faster than &
and more "inteligent"
Upvotes: 2
Reputation: 726
The expression are readed from left to right in addition to that the &&
has higher precedence than ||
.
So in your case it's would be like
if ((locClsTanken.PlaceID == -1 && locRwF.PlaceID > -1) || locClsTanken.DagPrijs == 0)
And the technical therm that you're looking for is Operators Precedence take a look to this link:Operators Precedence
Upvotes: 2