Left to right expression evaluation

David picture David · Dec 3, 2008 · Viewed 7k times · Source

In C# is it guaranteed that expressions are evaluated left to right?

For example:

myClass = GetClass();  
if (myClass == null || myClass.Property > 0)  
    continue;

Are there any languages that do not comply?

Answer

Tomalak picture Tomalak · Dec 3, 2008

You actually refer to a language feature called "short-circuiting logical expressions":

What this means is this: When the outcome of a logical expression cannot change anymore, e.g. when it is clear that the expression will evaluate to "true" or "false" no matter what, remaining parts of the expression will not be evaluated.

For example, C#, Java or JavaScript do that, and you can rely on it in those languages (to answer your question).

In your case, if MyClass is not null:

  • MyClass == null evaluates to false
  • since it is an "or" expression, the second part still can change the result, so it is evaluated
  • myClass.Property > 0 determines the end result

if MyClass is null:

  • MyClass == null evaluates to true
  • since it is an "or" expression, it does not matter what follows
  • no more evaluation is done, the end result is true

There are languages that do not short-circuit logical expressions. Classical VB is an example, here "myClass.Property > 0" would be evaluated and produce an error if MyClass was null (called "Nothing" in VB).