10

Possible Duplicate:
Why are there no ||= or &&= operators?

By pure accident I found out today that

 a &= GetBool();

is NOT the same as

 a = a && GetBool();

I must have misunderstood that for years. In the first Example, "GetBool()" is executed even if "a" is false. In the second, it isn't.

Is there anything to achieve something like "&&=" in C#?

Community
  • 1
  • 1
Ole Albers
  • 7,645
  • 7
  • 56
  • 130
  • 3
    @Soohjun: That should be `false` instead of `true`. – leppie May 09 '12 at 09:33
  • 5
    I believe Eric blogged on why `&&=` is not available .....Ahh here it is http://blogs.msdn.com/b/ericlippert/archive/2012/04/19/null-is-not-false-part-three.aspx – V4Vendetta May 09 '12 at 09:38
  • 1
    See [this answer by Eric Lippert](http://stackoverflow.com/questions/6346001/why-are-there-no-or-operators). – user703016 May 09 '12 at 09:40
  • @HenkHolterman: Bitwise and boolean is exactly the same when the type is a bit/boolean. – leppie May 09 '12 at 09:43
  • @HenkHolterman: I think I am confusing myself, with my own comments. Deleting :) – leppie May 09 '12 at 09:46

2 Answers2

6

Is there anything to achieve something like "&&=" in C#?

Well, you can write

a = a && getBool();

instead... I can't think of many situations where I'd actually want to do anything different, to be honest. Even the above is pretty rare, IME.

There's no compound assignment operator defined for &&, || or ?? (which are the obvious "short-circuiting" operators). See section 7.17 of the C# 4 spec for the full list of compound assignment operators, and section 7.17.2 for more details about what exactly compound assignment does.

Jon Skeet
  • 1,261,211
  • 792
  • 8,724
  • 8,929
4

From the documentation:

An expression using the &= assignment operator, such as

x &= y

is equivalent to

x = x & y

except that x is only evaluated once. The & operator performs a bitwise logical AND operation on integral operands and logical AND on bool operands.

I would say, to avoid evaluation of y when not necessary, use

x = x && y

and to avoid evaluation of x twice (whatever this means), use

x &= y

You can't combine both.

Micro-optimized (at least for a theoretical case), it would be:

if (x) x = y;

You don't need to do anything if x is already false.

Stefan Steinegger
  • 60,747
  • 15
  • 122
  • 189
  • 3
    "evaluated once" is meant for more complex cases, for instance if you have `x[i+3] = x[i+3] & y;` Then `i+3` is calculated twice, obviously! – Mr Lister May 09 '12 at 09:43
  • @Mr Lister: This makes sense, I didn't consider this. There are also properties, where you can use the &= operator, which may have an arbitrary complex implementation (if this is a good design aside). – Stefan Steinegger May 09 '12 at 09:57