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>
toSystem.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)
{
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With