Béranger
Béranger

Reputation: 673

Conditional logical operator working with =

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();

Upvotes: 1

Views: 105

Answers (4)

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37000

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.

Upvotes: 0

Gilad Green
Gilad Green

Reputation: 37299

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

Upvotes: 1

dymanoid
dymanoid

Reputation: 15197

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

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

Upvotes: 3

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186718

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

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

Upvotes: 2

Related Questions