How can I make this generic?
class AtomicReference
{
private Object _value;
public AtomicReference()
{
_value = new Object();
}
public AtomicReference(Object value)
{
OptimisticSet(value);
}
public Object CompareAndSet(Object newValue)
{
return Interlocked.Exchange(ref _value, newValue);
}
public void OptimisticSet(Object newValue)
{
do {
} while (_value == Interlocked.CompareExchange(ref _value, _value, newValue));
}
public Object Get()
{
return _value;
}
}
My failed attempt:
class AtomicReference<T>
{
private T _value;
public AtomicReference()
{
}
public AtomicReference(T value)
{
Set(value);
}
public T CompareAndSet(T newValue)
{
// _value is not an object that can be referenced
return Interlocked.Exchange(ref _value, newValue);
}
public void OptimisticSet(T newValue)
{
// I can't use the operator== with type T
do{}while(_value == CompareAndSet(newValue));
}
public T Get()
{
return _value;
}
}