Follow up question to a previous question, this has been identified as a co-variance issue. Taking this one step further, if I modify IFactory as follows:
class Program
{
static void Main(string[] args)
{
IFactory<IProduct> factory = new Factory();
}
}
class Factory : IFactory<Product>
{
}
class Product : IProduct
{
}
interface IFactory<out T> where T : IProduct
{
List<T> MakeStuff();
}
interface IProduct
{
}
I get:
Invalid variance: The type parameter T must be invariantly valid on Sandbox.IFactory.MakeStuff(). T is covariant.
Why is this not invariantly valid? How can/should this be resolved?
@Craig’s answer is correct. To resolve, change it to:
EDIT: As to the why, look at the definition of IEnumerable<T> Interface:
Note that the IList<T> Interface does not have the out keyword. Variance is supported for generic type parameters in interfaces and delegates, not classes, so it doesn’t apply to List<T>.