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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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 == nullevaluates to falsemyClass.Property > 0determines the end resultif MyClass is null:
MyClass == nullevaluates to trueThere 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).