System.Threading.Interlocked.CompareExchange operator provides atomic (thus thread-safe) C# implementation of the Compare-And-Swap operation.
For example int i = 5; Interlocked.CompareExchange(ref i, 10, 5); After this command, the int i would have a value = 10. And also the compare and exchange happens atomically (single operation).
When I tried using this with a class instance, the compare fails and the values are not exchanged.
public class X
{
public int y;
public X(int val) { y = val; }
}
Now when I do
X a = new X(1);
X b = new X(1);
X c = new X(2);
Interlocked.CompareExchange<X>(ref a, c, b);
The compare and Exchange operation fails. So, I overrided the Equals and the == operator for the class X as
public override bool Equals(object obj) { return y == ((X) obj).y; }
So, now I get Interlocked.Equals(a,b) as true, but the CompareExchange operations still fails.
Is there any method to do this? I want to compare two class instances and assign one of them a value based on the comparision.