Covariance and Contravariance in Generics | Microsoft Docs[
^]
It's not a simple topic. :)
Imagine a world where
I<Derived>
was equivalent to
I<Base>
. That would mean that the following code would work:
class Base { }
class Derived : Base { }
class OtherDerived : Base { }
List<Derived> list = new List<Derived>();
IList<Base> baseList = list;
baseList.Add(new OtherDerived());
Now the list is broken - it can only contain
Derived
objects, but we've managed to sneak a
OtherDerived
instance into it.
For your sample to work, your
ITest<T>
interface needs to be covariant:
interface ITest<out T> where T : class, IBaseObject
{
}
With that one change in place, your code will work as expected.
However, your interface will now be subject to the restrictions placed on a covariant interface: you cannot use the type parameter as a method parameter, not even an
out
parameter; nor can you use it as the type of a writeable property.