views:

116

answers:

2

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;
    }
}
+9  A: 

You need to constrain T to be a reference type, like this:

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 a property:

public T Value {
    get { return _value; }
    set { while(_value == CompareAndSet(value)); }
}
SLaks
Thanks again! :) SLaks is on top of the game!
Lirik
Constraints on Type Parameters (C# Programming Guide) - http://msdn.microsoft.com/en-us/library/d5x73970.aspx
kristian
A: 

I don't have VS 2005 installed at home to help debug your solution, but I think you need to constrain T. Here are some some resources to assist:

Generics C#

Generics Explained (.NET Framework version 2.0)

0A0D