C# how to protect the field of an atomic class?

950 views Asked by At

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?

2

There are 2 answers

6
SLaks On BEST ANSWER

Even if you try, it is not possible to return a reference to a field in C# (without unsafe code) or Java. (I don't mean a reference to an object)

You can simply write return _value; your callers will not be able to write to the field.

1
SLaks On

C# does not support C++'s const keyword, which allows for immutable references to mutable objects.

There are only two ways to do what you're asking.

  • You could clone the object whenever you return it. Note that this will only work for clonable objects, and it'll be quite slow.
  • You could only support value types.