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
  • 661
  • 8
  • 21

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,253
  • 4
  • 36
  • 61
2

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

  bool myBool = ...;
  myBool = Foo() && myBool;
Dmitry Bychenko
  • 165,109
  • 17
  • 150
  • 199
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
  • 35,761
  • 7
  • 54
  • 89
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
  • 20,880
  • 13
  • 75
  • 99
MakePeaceGreatAgain
  • 33,293
  • 6
  • 51
  • 100