1

How can I use an out parameter on a generic type in my interface, and reuse this type as parameter of a method, or as return of a function which is not covariante ?

Please see the sample (my real case is the "Add(T item)", others are tests) :

public interface ITestAdapter<out T>
{
    void Clear(); // Compile

    T GetItemAt(int index); // Compile

    void Add(T item); // ERROR:  Invalid variance: The type parameter 'T' must be contravariantly valid on 'ITestAdapter<T>.Add(T)'. 'T' is covariant.
    IList<T> GetInnerList(); //ERROR: Invalid variance: The type parameter 'T' must be invariantly valid on 'ITestAdapter<T>.GetInnerList()'. 'T' is covariant.

    IEnumerable<T> GetInnerAsEnumerable(); // Compile
}

public class TestAdapter<T> : ITestAdapter<T>
{
    public TestAdapter(IList<T> innerList)
    {
        this._innerList = innerList;
    }

    private readonly IList<T> _innerList;

    public void Clear()
    {
        this._innerList.Clear();
    }

    public void Add(T item)
    {
        this._innerList.Add(item);
    }

    public T GetItemAt(int index)
    {
        return this._innerList[index];
    }

    public IList<T> GetInnerList()
    {
        return this._innerList;
    }

    public IEnumerable<T> GetInnerAsEnumerable()
    {
        return this._innerList;
    }
}

public class A { }
public class AB : A { }

public class Test
{
    public static void Doy()
    {
        var list = new List<AB>();
        var typed = new TestAdapter<AB>(list);
        var boxed = default(ITestAdapter<A>);
        boxed = typed; // OK;
    }
}
Manofgoa
  • 81
  • 2
  • 5
  • Possible duplicate of [Why am I getting "The type parameter must be invariantly valid..." error?](http://stackoverflow.com/questions/6142747/why-am-i-getting-the-type-parameter-must-be-invariantly-valid-error) – Evan Trimboli May 18 '17 at 12:46
  • Not exactly, as you can see in my sample, the GetInnerList(); is just a test, and the solution (GetInnerAsEnumerable()) is the same as in the post you refer. I my case, I want use the generic type as parameter (the Add() method). – Manofgoa May 18 '17 at 12:59
  • The reasoning is the same. Because the type is contravariant, you can't use it as an "input". A better explanation is here: http://stackoverflow.com/a/5043054/149436 – Evan Trimboli May 18 '17 at 13:03

0 Answers0