HappyNomad
HappyNomad

Reputation: 4548

Negate a boolean based on another boolean

What's the short, elegant, bitwise way to write the last line of this C# code without writing b twice:

bool getAsIs = ....
bool b = ....

getAsIs ? b : !b

Upvotes: 23

Views: 5162

Answers (3)

drf
drf

Reputation: 8699

The truth table can be expressed as:

getAsIs    b    getAsIs ? b : !b
--------------------------------
0          0    1
0          1    0
1          0    0
1          1    1

The result can be expressed as:

result = (getAsIs == b);

Upvotes: 50

Bort
Bort

Reputation: 7618

I think it's

var foo = !(getAsIs ^ b)

Short, elegant, but definitely a head-scratcher!

Upvotes: 4

horgh
horgh

Reputation: 18534

Try using binary XOR (^ Operator (C# Reference)):

bool getAsIs = true;
bool b = false;

bool result = !(getAsIs ^ b);

Upvotes: 9

Related Questions