Search code examples
c#interfacecovariancebindinglist

c# covariance with Interface and BindingList


Could not understand problem here:

public interface ILinkedTabularSectionManager<out T1> where T1 : TabularBusinessObject
{
    T1 LinkedTabularBusinessObject { get; }

    BindingList<T1> DataSource { get; }
}

C# Invalid variance: The type parameter must be invariantly valid on. is covariant.

Error is related to BindingList declaration.

Thanks.


Solution

  • A covariant interface can only return covariant generic types that use the type varable. That means the return value of the DataSource property must also be covariant. BindingList is not covariant, so it can not be returned by a method or property of a covariant interface. The closest covariant interface to a BindingList<T> is IReadOnlyList<T> (BindingList<T> implements it), so you might want to use this one:

    public interface ILinkedTabularSectionManager<out T1> where T1 : TabularBusinessObject
    {
        T1 LinkedTabularBusinessObject { get; }
    
        IReadOnlyList<T1> DataSource { get; }
    }