3

A co-worker and I had a discussion about what style is used to express the AND NOT condition in C#. While both methods work, we disagree about the style of the operator.

He says that && ! is the preferred way. For example:

db.Widget.Where(w => w.Name == "Foo" && !w.IsBlue);

I say that that will work, but &! will work. For example:

db.Widget.Where(w => w.Name == "Foo" &! w.IsBlue);

I used to have a book about C# style, but do not remember seeing this covered. What does SO use?

Andy Evans
  • 6,997
  • 18
  • 72
  • 118
  • 4
    `&&` will short-circuit if the first operand is `false`, while `&` will not. – 4castle Mar 17 '17 at 04:20
  • 2
    Highly recommend against using the bitwise `&` for this... while it may work, it is not natural and will have some coders scratching head to figure out intent. And in case it needed spelling out --- there is no "and not" operator here -- just the three operators bitwise and, boolean and, and boolean not. – Cory Nelson Mar 17 '17 at 04:22
  • 1
    There is no such thing as "the `&&!` operator", nor "the `&!` operator". There is just the `&&` and `&` operators, and the `!` operator which can be applied to either operand of the `&&` and `&` operator. See marked duplicates for the difference between `&&` and `&`. – Peter Duniho Mar 17 '17 at 04:52
  • 1
    @CoryNelson: Try to not think of `&` as "bitwise" because it is perfectly legal on `bool`. Better to think of it as eager vs lazy. – Eric Lippert Mar 17 '17 at 04:55

1 Answers1

1

They both are different logical and operators. && is logical and operator while & For integral types computes the logical bitwise AND of its operands. For bool operands, & computes the logical AND of its operands, reference. One difference is that && will short circuit whereas & will not.

In this particular case the logical and is more easy to understand because it is most commonly used for logical and. As mentioned earlier the && will short-circuit the condition e.g. if && gets false in the condition statement the further conditions on right won't be evaluated, but & wont short-circuit. See the example given below.

int a = 1;
int b = 2;
int c = 3;
bool r = a == 2 && ++b == 2;
Console.WriteLine(b);
r = a == 2 & ++b == 2;
Console.WriteLine(b);

Output

2
3

In the above example using && if a is not 1 then remaining condition wont be evaluated which is not case with bitwise &. Due to short circuiting of && the b is not incremented but with & the value of b is incremented as short-circuiting did not applied.

In my opinion using && is more appropriate here as it makes code more understandable along with short-circuiting.

Adil
  • 146,340
  • 25
  • 209
  • 204
  • 1
    In C#, `&` on bool is _not_ the bitwise and operator, but the logical and operator without short circuit: https://msdn.microsoft.com/en-us/library/sbf85k1c.aspx – king_nak Mar 17 '17 at 06:56
  • Thanks @king_nak for letting me correct the mistake. – Adil Mar 17 '17 at 07:25