Is there XNOR (Logical biconditional) operator in C#?

C#BooleanBoolean Operations

C# Problem Overview


I'm new to C# and could not find XNOR operator to provide this truth table:

a  b    a XNOR b

T T T T F F F T F F F T

Is there a specific operator for this? Or I need to use !(A^B)?

C# Solutions


Solution 1 - C#

XNOR is simply equality on booleans; use A == B.

This is an easy thing to miss, since equality isn't commonly applied to booleans. And there are languages where it won't necessarily work. For example, in C, any non-zero scalar value is treated as true, so two "true" values can be unequal. But the question was tagged [tag:C#], which has, shall we say, well-behaved booleans.

Note also that this doesn't generalize to bitwise operations, where you want 0x1234 XNOR 0x5678 == 0xFFFFBBB3 (assuming 32 bits). For that, you need to build up from other operations, like ~(A^B). (Note: ~, not !.)

Solution 2 - C#

XOR = A or B, but Not A & B or neither (Can't be equal [!=])
XNOR is therefore the exact oppoiste, and can be easily represented by == or ===.

However, non-boolean cases present problems, like in this example:

a = 5
b = 1

if (a == b){
...
}

instead, use this:

a = 5
b = 1

if((a && b) || (!a && !b)){
...
}

or

if(!(a || b) && (a && b)){
...
}

the first example will return false (5 != 1), but the second will return true (a[value?] and b[value?]'s values return the same boolean, true (value = not 0/there is a value)

the alt example is just the reversed (a || b) && !(a && b) (XOR) gate

Solution 3 - C#

No, You need to use !(A^B)

Though I suppose you could use operator overloading to make your own XNOR.

Solution 4 - C#

You can use === operator for XNOR. Just you need to convert a and b to bool.

if (!!a === !!b) {...}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontrailmaxView Question on Stackoverflow
Solution 1 - C#Keith ThompsonView Answer on Stackoverflow
Solution 2 - C#Braden BestView Answer on Stackoverflow
Solution 3 - C#GriffinView Answer on Stackoverflow
Solution 4 - C#user7797323View Answer on Stackoverflow