I\'m having a little trouble understanding how I would use covariance and contravariance in the real world.
So far, the only examples I\'ve seen have been the same o
The converter delegate helps me to visualise both concepts working together:
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();