Answer to initial question
You're currently trying to convert a single element of type TDerived
to a sequence of type Base
. I wouldn't expect your Cast
call to work either, as TDerived
doesn't implement IEnumerable
- I suspect you've actually got that to work in a different situation instead.
I suspect you actually meant:
void Test3<TDerived>(IEnumerable<TDerived> derived) where TDerived : Base
{
IEnumerable<Base> b = derived;
}
That compiles with no problems.
Answer to edited question
Okay, now we've got the real problem between two type parameters, the issue is that the compiler doesn't know that they're reference types - which is required for generic variance. You can fix that with a class
constraint on TDerived
:
void Test3<TDerived, TBase>(IEnumerable<TDerived> derived)
where TDerived : class, TBase
{
IEnumerable<TBase> b = derived;
}