Error when trying to implement interface with generic returned value

Hi guys,

I’m trying to implement an interface which define a GetValue and SetValue methods with generic value. My point would be to be able to have a list initialized with the interface type in order to be able to store any type that implement this interface. Unfortunately I have an error and this is why I need your help :slight_smile:

The code :

public interface IConfigValue{

        T GetValue<T> ();
        void SetValue<T> (T val);
    }

    [System.Serializable]
    public class ConfigValue<T> : IConfigValue{

        public string ID;
        public T value;
        public Type valueType;

        public ConfigValue(string ID, T val){
           
            this.ID = ID;
            this.value = val;
            this.valueType = val.GetType();
        }

        public void SetValue<T>(T val){

            this.value = val;
        }

        public T GetValue<T>(){

            return this.value;
        }
    }

The error : ConfigValue.cs(34,25): error CS0029: Cannot implicitly convert type T' to T’

So how would you do if you want to create a List values ? I don’t want to declare a list for each type like List<ConfigValue> intValues etc.

Thanks

Your IConfigValue has generic methods. It implies that the method contains the generic type.

So when implemented the coming from GetValue is not the same T from ConfigValue… they’re distinctly different types. And since ‘value’ is of the type T that is passed to ConfigValue and not of the type passed to GetValue, it does not know if it can be converted between.

I think you maybe intended the interface to be defined as follows:

public interface IConfigValue<T>
{
    T GetValue();
    void SetValue(T val);
}

No on the methods.