[Answered] How are the conditions in an if evaluated?

…another question that I feel I should have been able to find the answer to, but probably fail at combining search words for…

How are conditions in a C# if-statement evaluated? If I have

if( A || B )

will B be calculated at all if A is false? (EDIT: I mean if A is TRUE, of course, silly old me…)

(I want to call it “lazy evaluation”, but I might be remembering my terminology incorrectly.)

In this example; yes. But that has probably more to do with your example (the overall if statement could still come out true, if B is true), than what you are asking about. At least it feels like your question has more depth, technically, than what I’m answering here. Did you mean: “Will B be calculated at all, if A is true?”

ZOMGWTFBBQ, yes I did. Thanks for catching that rather silly error!

And the answer is no, B won’t be evaluated at all. It is in fact explicitly mentioned in the pages for and || in the .Net manual:
http://msdn.microsoft.com/en-us/library/2a723cdk(VS.71).aspx

Ah, great, that’s what I was looking for. As I suspected, I was just searching with the wrong parameters. Thank you for the answer!

And it’s great knowledge for a n00b wannabe scripter like me, who hadn 't even considered things like this. So that means it’s an optimization if you place the simplest-to-evaluate statements first in such an arrangement. Never thought about that. That’s the prize for being self taught. You have no idea what you have missed of valuable information :slight_smile:

Yep! Also, it means you can “safely” do checks like

if(x == null || x.param == null)

without getting a null pointer exception for it trying to get the param in the second check from a null x. Quite handy.