Vinicius
Vinicius

Reputation: 1365

Using generics with IEnumerable in base class constructor

Why does this code gives this error?

Argument type 'System.Collections.Generic.IEnumerable<T>' is not assignable to parameter type 'System.Collections.Generic.IEnumerable<[...].IExample>'

public interface IExample { }

public class BaseClass
{
    public BaseClass(IEnumerable<IExample> a) { }
}

public class FailingClass<T> : BaseClass
    where T : IExample
{
    public FailingClass(IEnumerable<T> a): base(a) { } //error here on base(a)
}       

Upvotes: 0

Views: 113

Answers (1)

thomas
thomas

Reputation: 2578

You are missing the class constraint to T within FailingClass. IEnumerable<T> has a type parameter marked as covariant. Covariance enables you to use a more derived type than originally specified. Variance in general applies to reference types only.

So what the class constraint actually does here is enforcing a constraint to pass a reference type. If you were to pass in a value type for T, that type parameter is invariant for the resulting constructed type and does not suffice IEnumerable<T>.

using System.Collections.Generic;

public interface IExample { }

public class BaseClass
{
    public BaseClass(IEnumerable<IExample> a) { }
}

public class FailingClass<T> : BaseClass
    where T : class, IExample
{
    public FailingClass(IEnumerable<T> a): base(a) { } //error here on base(a)
}  

Upvotes: 3

Related Questions