-1

In C#, if we have the following code:

if (condition1 && condition2)

and condition1 turns out to be false, is condition2 still checked or does the execution simply continue after the if statement?

rene
  • 41,474
  • 78
  • 114
  • 152
user4520
  • 3,401
  • 1
  • 27
  • 50
  • -1 No research effort. https://www.google.com/#q=c%23+%26%26 – James Apr 13 '14 at 10:41
  • I edited your title to remove the tags. See [this meta post](http://meta.stackexchange.com/questions/19190/should-questions-include-tags-in-their-titles) for the reasoning behind that. – rene Apr 13 '14 at 11:49

3 Answers3

3

Firstly it evaluates condition1, then if it is true then it will evaluates condition2. It will not evaluate condition2 if condition1 is false. This is called short-circuit evaluation.

Zbigniew
  • 27,184
  • 6
  • 59
  • 66
1

No the && operator is short circuiting. The & operator is however not and all of the expressions will be evaluated if you use that.

satnhak
  • 9,407
  • 5
  • 63
  • 81
1

Yes C# does short circuit evaluation of boolean expressions. Therefore

if ( X && Y() )

1) X will be executed first

2) Y will only be executed if and only if X returns true

This applies to all boolean expressions and not just those in an IF statement...Check this in the C# Specification available online at MSDN. section 14.11.1

you can use also the & and in this case it won't be a short circuite evaluation because

& is the "and" operator used for bit manipulation. && is the "and" operator used to evaluate logically expressions.

JustGreat
  • 551
  • 1
  • 11
  • 26