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
Here's what I put together to help me understand the difference
public interface ICovariant { }
public interface IContravariant { }
public class Covariant : ICovariant { }
public class Contravariant : IContravariant { }
public class Fruit { }
public class Apple : Fruit { }
public class TheInsAndOuts
{
public void Covariance()
{
ICovariant fruit = new Covariant();
ICovariant apple = new Covariant();
Covariant(fruit);
Covariant(apple); //apple is being upcasted to fruit, without the out keyword this will not compile
}
public void Contravariance()
{
IContravariant fruit = new Contravariant();
IContravariant apple = new Contravariant();
Contravariant(fruit); //fruit is being downcasted to apple, without the in keyword this will not compile
Contravariant(apple);
}
public void Covariant(ICovariant fruit) { }
public void Contravariant(IContravariant apple) { }
}
tldr
ICovariant apple = new Covariant(); //because it's covariant
IContravariant fruit = new Contravariant(); //because it's contravariant