Search code examples
c#genericsinterlocked

Interlocked.Exchange can't be used with generics?


I'm writing a generic class where I need to use Interlocked.

T test1, test2;
Interlocked.Exchange<T>(ref test1, test2);

This won't compile. So am I forced to use Exchange(Object, Object) instead even tho MSDN advices not to use it that way?


Solution

  • This will work, provided your generic class has the same constraints as Interlocked.Exchange<T>, namely, where T: class.

    From the docs for Interlocked.Exchange:

    This method only supports reference types