Search code examples
c#logicoperator-precedence

C# logic order and compiler behavior


In C#, (and feel free to answer for other languages), what order does the runtime evaluate a logic statement?

Example:

DataTable myDt = new DataTable();
if (myDt != null && myDt.Rows.Count > 0)
{
    //do some stuff with myDt
}

Which statement does the runtime evaluate first -

myDt != null

or:

myDt.Rows.Count > 0

?

Is there a time when the compiler would ever evaluate the statement backwards? Perhaps when an "OR" operator is involved?


& is known as a logical bitwise operator and will always evaluate all the sub-expressions

What is a good example of when to use the bitwise operator instead of the "short-circuited boolean"?


Solution

  • C# : Left to right, and processing stops if a non-match (evaluates to false) is found.