I have an interface with a covariant type parameter:
interface I<out T>
{
T Value { get; }
}
Additionally, I have a non-generic base class and another deriving from it:
class Base
{
}
class Derived : Base
{
}
Covariance says that an I<Derived>
can be assigned to an I<Base>
, and indeed I<Base> ib = default(I<Derived>);
compiles just fine.
However, this behavior apparently changes with generic parameters with an inheritance constraint:
class Foo<TDerived, TBase>
where TDerived : TBase
{
void Bar()
{
I<Base> ib = default(I<Derived>); // Compiles fine
I<TBase> itb = default(I<TDerived>); // Compiler error: Cannot implicitly convert type 'I<TDerived>' to 'I<TBase>'. An explicit conversion exists (are you missing a cast?)
}
}
Why are these two cases not treated the same?