Search code examples
c#boolean-expression

In what order are boolean expressions evaluated


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


Solution

  • && 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