Matt
Matt

Reputation: 697

Constraint on generic type cannot be used in IEnumerable?

There probably is a question on this already, but I wasn't able to come up with the search terms to find an answer..

I'm probably missing something obvious here, but why am I not allowed to do the following, which gives the error:

"Argument 1: cannot convert from System.Collections.Generic.IEnumerable<TType> to System.Collections.Generic.IEnumerable< Test.A>"

whilst making the call to DoSomething?

public interface A
{
    void Foo();
}

public class B : A
{
    public void Foo()
    {
    }
}

class Test<TType> where TType : A
{
    public Test(IEnumerable<TType> testTypes)
    {
        DoSomething(testTypes);
    }

    void DoSomething(IEnumerable<A> someAs)
    {
    }
}

whilst it is, of course, OK to do this:

class Test
{
    public Test(IEnumerable<B> testTypes)
    {
        DoSomething(testTypes);
    }

    void DoSomething(IEnumerable<A> someAs)
    {
    }
}

Upvotes: 5

Views: 596

Answers (1)

Jakub Lortz
Jakub Lortz

Reputation: 14894

Variance works only for reference types. In your code TType can also be a value type. If you add a class constraint, the code will compile

class Test<TType> where TType : class, A
{
    public Test(IEnumerable<TType> testTypes)
    {
        DoSomething(testTypes);
    }

    void DoSomething(IEnumerable<A> someAs)
    {
    }
}

You can find a detailed explanation here

Upvotes: 7

Related Questions