The generic type restriction cannot be used in IEnumerable?

Probably this already has a question, but I could not find the search terms to find the answer.

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

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

during a DoSomething call?

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

although it is of course OK to do this:

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

    void DoSomething(IEnumerable<A> someAs)
    {
    }
}
+4
source share
1 answer

Deviation only works for reference types. Your code TTypemay also have a value type. If you add a restriction class, the code will compile

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

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

A detailed description can be found here.

+5
source

Source: https://habr.com/ru/post/1610190/


All Articles