visual studio – List of more derived objects gioves compile error in a C# interface implementation


Can someone explain me why C# doesn’t support the following contruct ?

I have the following interface declaration:

public interface IConfigurationResult
{
    public int ItemId { get; }

    public string ItemCode { get; }

    public IList<IConfigurationVariable> Variables { get; }
}

The interface IConfigurationVariable is implemented in the class ConfigurationVariable that for semplicity I won’t add here.

Then I have the following class definition:

public class ConfigurationResult : IConfigurationResult
{
    public int ItemId { get; }

    public string ItemCode { get; }

    public List<ConfigurationVariable> Variables { get; }//This returns a compilation error
}

Why the error ? List implements IList and ConfigurationVariable implements IConfigurationVariable, so I’m declaring a more derived list with a more derived class, it should be fine, instead I get the error that Variables is not defined.

Ok, I know that List does allow changes to the list why IList doesn’t, I know about the covariance and contravariance story, but if I need the declaration of the interface to be shared with other libraries and I would like to share the interface and not the class, to hide the implemenation (not necesary) that is not needed in the libraries, why not giving me the possibility of doing it ? It should exist a way to make it work… I cannot understand that.

Maybe there is someone smarter than me (many billions for sure) that can offer an explanation.. and most importantly, a solution.

Thank you in advance.

Leave a Reply

Your email address will not be published. Required fields are marked *