In some situations I need to cast down an object to an interface to fit my needs, which implicitly requires to cast down type arguments of generic interfaces.
Example
ICage<TAnimal>
is the interface for a Cage
of an animal of type IAnimal
public interface ICage<TAnimal>
where TAnimal : IAnimal<IOwner>
public class Cage<TAnimal> : ICage<TAnimal>
where TAnimal : IAnimal<IOwner>
public interface IAnimal<out TOwner>
where TOwner : IOwner
IAnimal
needs an Owner of type IOwner
public abstract class Mammal<TOwner> : IAnimal<TOwner>
where TOwner : IOwner
A Mammal is a type of Animal with an Owner of type IOwner
.
public class Human : IOwner
A Human
is a type of IOwner
public class Dog<TOwner> : Mammal<TOwner>
where TOwner : IOwner
A Dog is a type of Mammal.
Now putting everything together:
var cage = new Cage<Mammal<IOwner>>();
var me = new Human()
{
Name = "Hakim"
};
var dog = new Dog<Human>();
dog.Owner = me;
cage.Add((Mammal<IOwner>)dog);
In the last line I get a compile time error CS0030 telling me that I can not convert Dog to Mammel.