private void ContravarianceExample() { ConsoleExtensions .WriteColoredLine(Resources.ContravarianceExampleRunning, ConsoleColor.Cyan); // A contravariant type in an interface or delegate can be converted to a more SPECIFIC // type. // Interface: IContravariant<Fruit> to IContravariant<Apple> IContravariant <Apple> appleContravariantInterface = this.fruitContravariantInterface; // Delegate: Contravariant<Fruit> to Contravariant<Orange> Contravariant <Orange> orangeContravariantDelegate = this.fruitContravariantDelegate; const int AppleQuality = 75; const int OrangeQuality = 60; var appleValue = appleContravariantInterface.GetValue( new Apple(AppleColor.Red, AppleQuality)); var orangeValue = orangeContravariantDelegate(new Orange(OrangeQuality)); Console.WriteLine( Resources.ContravarianceExampleAppleValue, nameof(appleValue), appleValue); Console.WriteLine( Resources.ContravarianceExampleOrangeValue, nameof(orangeValue), orangeValue); Console.WriteLine(); }
public void Contravariance() { IContravariant <Fruit> fruit = new Contravariant <Fruit>(); IContravariant <Apple> apple = new Contravariant <Apple>(); Contravariant(fruit); //fruit is being downcasted to apple, without the in keyword this will not compile Contravariant(apple); }
private static void Contravariance() { IContravariant <Apple> fruit = new Contravariant <Fruit>(); IContravariant <Apple> apple = new Contravariant <Apple>(); // IContravariant<Fruit> apple = new Contravariant<Apple>(); // not allowed Console.WriteLine(fruit.GetType()); Console.WriteLine(apple.GetType()); }
static void ContravariantAndCovariant() { IContravariant <BaseClass> iBaseClassA = new Contravariant <BaseClass>(); iBaseClassA.Method(new DerivedClass()); ICovariant <BaseClass> iBaseClassB = new Covariant <BaseClass>(); iBaseClassB.Method().Print(); }
static void Run() { ICovariant <Fruit> apple = new Covariant <Apple>(); //because it's covariant IContravariant <Apple> fruit = new Contravariant <Fruit>(); //because it's contravariant }