Jeff G
Jeff G

Reputation: 4677

Generic Method Fails to Utilize Covariance on IEnumerable<T>

I am wondering why the following code fails to compile, with the exception "Instance argument: cannot convert from 'System.Collections.Generic.IEnumerable<TImpl>' to 'System.Collections.Generic.IEnumerable<TInterface>'":

public static List<TInterface> Foo<TInterface, TImpl>(IEnumerable<TImpl> input)
    where TImpl : TInterface
{
    return input.ToList<TInterface>();
}

I know that I could change the return line to be input.Cast<TInterface>().ToList() instead, but want to understand why the code as written doesn't compile. In my mind, it seems as though the compiler should be able to verify that input can be implicitly cast to IEnumerable<TInterface>.

Upvotes: 2

Views: 38

Answers (1)

SLaks
SLaks

Reputation: 887469

Variance only works on classes.

Add class, to your constraint.

Demo

Upvotes: 4

Related Questions