When a method is assigned to a delegate, the covariant and inverter provide the flexibility to match the delegate type with the method signature. The covariant allows a method to have more derived return types than those defined in the delegate. The inverse method allows fewer derived parameter types than the delegate type.
Example 1: covariant
Description
This example shows how to use a delegate with a method with a return type, which is derived from the return type in the delegate signature. The data type returned by dogshandler is the dogs type, which is derived from the mammals type defined in the delegate.
class Mammals{}class Dogs : Mammals{}class Program{ // Define the delegate. public delegate Mammals HandlerMethod(); public static Mammals MammalsHandler() { return null; } public static Dogs DogsHandler() { return null; } static void Test() { HandlerMethod handlerMammals = MammalsHandler; // Covariance enables this assignment. HandlerMethod handlerDogs = DogsHandler; }}
Example 2: Inverter
Description
This example shows how to use a delegate with a method with a certain type of parameters, which are the base type of the delegate signature parameter type. If inverter is used, you can use one event handler instead of multiple independent handlers. For example, you can create an event handler that accepts the input parameters of eventargs, and use it with the button that uses the mouseeventargs type as the parameter. the mouseclick event can be used together with the textbox that sends the keyeventargs parameter. the keydown event is used together.
// Event hander that accepts a parameter of the EventArgs type.private void MultiHandler(object sender, System.EventArgs e){ label1.Text = System.DateTime.Now.ToString();}public Form1(){ InitializeComponent(); // You can use a method that has an EventArgs parameter, // although the event expects the KeyEventArgs parameter. this.button1.KeyDown += this.MultiHandler; // You can use the same method // for an event that expects the MouseEventArgs parameter. this.button1.MouseClick += this.MultiHandler;}