// Initialize delegate variables. public void RunCovarianceAndContravarianceDelegates() { // Use covariance to set ReturnPersonMethod = ReturnEmployee. ReturnPersonMethod = ReturnEmployee; // Use contravariance to set EmployeeParameterMethod = PersonParameter. EmployeeParameterMethod = PersonParameter; }
static void Main() { //Covariance Console.WriteLine("Vanilla Covariance"); ReturnPersonMethod = ReturnEmployee; ReturnPersonMethod(); Console.WriteLine(); //Func Covariance Console.WriteLine("Func Covariance"); ReturnPersonFunc = ReturnEmployee; ReturnPersonFunc(); Console.WriteLine(); //Contravariance Console.WriteLine("Vanilla Contravariance"); EmployeeParameterMethod = SomethingThatTakesAPerson; EmployeeParameterMethod(new Employee()); Console.WriteLine(); //Action contravariance Console.WriteLine("Action Contravariance"); EmployeeParameterAction = SomethingThatTakesAPerson; EmployeeParameterAction(new Employee()); Console.WriteLine(); //ContraCovariance Console.WriteLine("Vanilla ContraCovariance"); ReturnsPersonTakesEmployeeMethod = ReturnsEmployeeTakesPerson; ReturnsPersonTakesEmployeeMethod(new Employee()); Console.WriteLine(); //Anonymous Method Console.WriteLine("Anonymous Method"); Console.WriteLine(SomeFunction(2, 3)); Console.ReadLine(); }
/// <summary> /// Covariance lets a method return a value from a subclass of the result expected by a delegate. /// </summary> void CovarianceExample() { returnPersonMethod = ReturnEmployee; }