// Initialize delegate variables. public void RunCovarianceAndContravarianceDelegates() { // Use covariance to set ReturnPersonMethod = ReturnEmployee. ReturnPersonMethod = ReturnEmployee; // Use contravariance to set EmployeeParameterMethod = PersonParameter. EmployeeParameterMethod = PersonParameter; }
// Initialize delegate variables. private void Form1_Load(object sender, EventArgs e) { // Set ReturnPersonMethod = ReturnEmployee. // Covariance allows this because ReturnPersonDelegate // returns a Person and an Employee is a kind of Person. ReturnPersonMethod = ReturnEmployee; // Set EmployeeParameterMethod = PersonParameter. // Contravariance allows this because EmployeeParameterDelegate // takes an Employee as a parameter and an Employee is a kind of Person. // In other words, when you invoke the delegate's method you will // pass it an Employee and an Employee is a kind of Person so // PersonParameter can handle it. EmployeeParameterMethod = PersonParameter; }
private static void Main(string[] args) { // Set ReturnPersonMethod = ReturnEmployee. // Covariance allows this because ReturnPersonDelegate // returns a Person and an Employee is a kind of Person. ReturnPersonMethod = ReturnEmployee; // Set EmployeeParameterMethod = PersonParameter. // Contravariance allows this because EmployeeParameterDelegate // takes an Employee as a parameter and an Employee is a kind of Person. // In other words, when you invoke the delegate's method you will // pass it an Employee and an Employee is a kind of Person so // PersonParameter can handle it. 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> /// Contravariance lets a method take parameters that are from a superclass of the type expected by a delegate. /// </summary> void ContravarianceExample() { employeeParameterMethod = PersonParameter; }