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
// Contravariance
interface IGobbler {
void gobble(T t);
}
// Since a QuadrupedGobbler can gobble any four-footed
// creature, it is OK to treat it as a donkey gobbler.
IGobbler dg = new QuadrupedGobbler();
dg.gobble(MyDonkey());
// Covariance
interface ISpewer {
T spew();
}
// A MouseSpewer obviously spews rodents (all mice are
// rodents), so we can treat it as a rodent spewer.
ISpewer rs = new MouseSpewer();
Rodent r = rs.spew();
For completeness…
// Invariance
interface IHat {
void hide(T t);
T pull();
}
// A RabbitHat…
IHat rHat = RabbitHat();
// …cannot be treated covariantly as a mammal hat…
IHat mHat = rHat; // Compiler error
// …because…
mHat.hide(new Dolphin()); // Hide a dolphin in a rabbit hat??
// It also cannot be treated contravariantly as a cottontail hat…
IHat cHat = rHat; // Compiler error
// …because…
rHat.hide(new MarshRabbit());
cHat.pull(); // Pull a marsh rabbit out of a cottontail hat??