I'm trying to make an AtomicReference class in C# and I want to keep the field reference protected, but I also need to return the value in the get method:
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()
{
// Don't leak the field reference
const Object constVal = _value;
return constVal;
}
}
It's a bit of a clumsy way around the problem... I can't make the field readonly, because I need to be able to set it. Is there a better solution than mine?
UPDATE: Thanks for the quick responses! It was rightfully pointed out that the reference will be protected if I simply return _value. I also want to protect the _value from mutating. If I allow the _value to mutate outside of the AtomicReference, then it defeats the entire purpose of making this class... is there a way to achieve that?