I am having trouble understanding the difference between covariance and contravariance.
The converter delegate helps me to understand the difference.
delegate TOutput Converter(TInput input);
TOutput represents covariance where a method returns a more specific type.
TInput represents contravariance where a method is passed a less specific type.
public class Dog { public string Name { get; set; } }
public class Poodle : Dog { public void DoBackflip(){ System.Console.WriteLine("2nd smartest breed - woof!"); } }
public static Poodle ConvertDogToPoodle(Dog dog)
{
return new Poodle() { Name = dog.Name };
}
List dogs = new List() { new Dog { Name = "Truffles" }, new Dog { Name = "Fuzzball" } };
List poodles = dogs.ConvertAll(new Converter(ConvertDogToPoodle));
poodles[0].DoBackflip();