Search code examples
c#coding-efficiencycommutativity

C# Commutativity in if statements


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.


Solution

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