Search code examples
c#genericsxor

generic xor swap in c# for different types


I'm trying to make a function that can swap any 2 variables in c# whether they are reference or value types using the xor method. Would this work properly for that purpose?

public static void QuickSwap<T>(ref T a, ref T b)
{
    if (ReferenceEquals(a, b) || (typeof(T).IsValueType && a == b))
        return;
    a ^= b;
    b ^= a;
    a ^= b;
}

Solution

  • No, because the XOR operator in C# is only defined for integral types and bool.

    (There is no generic XOR operator on arbitrary types, since it would result in an invalid state, which contradicts the design goal of C# as a type-safe language: myClass1 ^ myClass2 would point to an invalid memory location, and the result of myStruct1 ^ myStruct2 would most likely be garbage as well.)