C# Commutativity in if statements

88 Views Asked by At

Is there a way to essentially write "and vice versa" in an if statement without writing the same code again but with "||"?

if (currentDirection == 1 && nextDirection == 2)
if ((currentDirection == 1 && nextDirection == 2) || (currentDirection == 2 && nextDirection == 1))

For example, here I would like it to also be true if currentDirection == 2 and nextDirection == 1 but it seems like there should be a better way to write the code than just the second way.

2

There are 2 best solutions below

0
V0ldek On BEST ANSWER

There's no built-in language construct for this, as it seems pretty niche.

You can easily make a helper function though:

bool UnorderedEq<T>(T a1, T a2, T b1, T b2) =>
    (a1, a2).Equals((b1, b2)) || (a1, a2).Equals((b2, b1));

If you care about performance, then this version for structs is probably better:

bool UnorderedEq<T>(in T a1, in T a2, in T b1, in T b2) where T: struct, IEquatable<T> =>
    (a1, a2).Equals((b1, b2)) || (a1, a2).Equals((b2, b1));
0
lidqy On

if, and only if, both comparands are guaranteed multiples of two you can do it with a straight and fast bitwise or:

    // as extension
        bool static BitMatch(this int bitMask, int val1, int val2)
        => val1 != 0 && val2 != 0 && bitMask!= 0 && ((val1 | val2) == bitMask);
    
    // call
       if ((1|2).BitMatch(currentDirection, nextDirection);