Reputation: 4548
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
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
Reputation: 7618
I think it's
var foo = !(getAsIs ^ b)
Short, elegant, but definitely a head-scratcher!
Upvotes: 4
Reputation: 18534
Try using binary XOR (^ Operator (C# Reference)):
bool getAsIs = true;
bool b = false;
bool result = !(getAsIs ^ b);
Upvotes: 9