Home > front end >  Using generics with IEnumerable in base class constructor
Using generics with IEnumerable in base class constructor

Time:07-12

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

CodePudding user response:

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)
}  
  • Related