1

I know that the following code will execute both the left and right expressions :

bool myBool = true;
myBool &= Foo();

Is there any way to write the same way (a kind of &&=) a code that will produce :

bool myBool = true;
myBool = myBool &&  Foo();

Instead of

myBool = myBool & Foo();
Béranger
  • 671
  • 8
  • 23

4 Answers4

3

There is no operator &&= in C#. So you can't do this.

For the list of all operators, take a look on MSDN.

dymanoid
  • 14,771
  • 4
  • 36
  • 64
2

If you want Foo() be executed, just swap:

  bool myBool = ...;
  myBool = Foo() && myBool;
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
1

Will this answer your question? (wasn't really clear)

bool myBool = true;
myBool = myBool ||  (!myBool && Foo());

Only if the myBool is false then the function will be executed

Gilad Green
  • 36,708
  • 7
  • 61
  • 95
0

As already mentioned there is no &&=-operator thus you can´t overload any. For a list of operators you can overload for any type see here. For assignement-operators there are no overloads defined at all:

Assignment operators cannot be overloaded, but +=, for example, is evaluated using +, which can be overloaded.

So your current approach using myBool && Foo(); is the way to go.

As mentioned on this post the IL for &= and & are equal making the former just syntactic sugar of the latter. So there´d be no real value on creating such an operator as all its use would be to get rid of a few characters.

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111