IList and Covariance
Now that I’m developing in .NET 4.0 I thought all my covariance problems were behind me. This was until I tried to use the following:
public class Animal {
public void AttackOtherAnimals(IList<Animal> animals) { }
}
public class Dog : Animal { }
Dog angryDog = new Dog();
List dogsToAttack = new List<Dog>();
angryDog.AttackOtherAnimals(dogsToAttack);
Turns out, IEnumerable<T> has support for covariance, IList<T> does not. I’d like to thank Marc Gravell for his excellent writeup on this.
One way around this (instead of dogsToAttack.Cast<Animal>().ToList()) is to use generics to accept any IList<T> where T is of type Animal.
public void AttackOtherAnimals(IList<T> animals) where T : Animal { }
Posted in .Net by Drew Freyling at April 21st, 2011.
Tags: .Net, Contravariance, Contravariant, Covariance, Covariant, Generics
Tags: .Net, Contravariance, Contravariant, Covariance, Covariant, Generics
