Tim
Tim

Reputation: 101

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;
}

Upvotes: 0

Views: 432

Answers (2)

Adrian Bhagat
Adrian Bhagat

Reputation: 203

There's no need to write a function to swap two values. You can just use a tuple:

(a, b) = (b, a);

Upvotes: 2

Heinzi
Heinzi

Reputation: 172220

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.)

Upvotes: 1

Related Questions