Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constraint on generic type cannot be used in IEnumerable?

Tags:

c#

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)
    {
    }
}
like image 256
Matt Avatar asked Oct 04 '15 18:10

Matt


1 Answers

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

like image 86
Jakub Lortz Avatar answered Nov 14 '22 21:11

Jakub Lortz