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;
}
}