C # How to create a common class?

How to do it?

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 unsuccessful 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;
    }
}
+3
source share
2 answers

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)); }
}
+11
source

I do not have VS 2005 installed at home to help debug your solution, but I think you need to limit T. Here are some resources to help:

Generics C #

Understanding General Concepts (.NET Framework Version 2.0)

0
source

Source: https://habr.com/ru/post/1724455/


All Articles