You need constrain to T be a reference type, for example:
class AtomicReference<T> where T : class {
private T _value;
public AtomicReference() { }
public AtomicReference(T value) {
OptimisticSet(value);
}
public T CompareAndSet(T newValue) {
return Interlocked.Exchange(ref _value, newValue);
}
public void OptimisticSet(T newValue) {
while (_value == CompareAndSet(newValue));
}
public T Get() {
return _value;
}
}
EDIT : I would recommend that you also replace the methods with the property:
public T Value {
get { return _value; }
set { while(_value == CompareAndSet(value)); }
}
source
share