diff --git a/docs/csharp/programming-guide/concepts/covariance-contravariance/snippets/using-variance-in-delegates/ContravarianceExample.cs b/docs/csharp/programming-guide/concepts/covariance-contravariance/snippets/using-variance-in-delegates/ContravarianceExample.cs new file mode 100644 index 0000000000000..0ab038d2b1b90 --- /dev/null +++ b/docs/csharp/programming-guide/concepts/covariance-contravariance/snippets/using-variance-in-delegates/ContravarianceExample.cs @@ -0,0 +1,133 @@ +using System; + +namespace ContravarianceExample +{ + // + // Custom EventArgs classes to demonstrate the hierarchy + public class KeyEventArgs(string keyCode) : EventArgs + { + public string KeyCode { get; set; } = keyCode; + } + + public class MouseEventArgs(int x, int y) : EventArgs + { + public int X { get; set; } = x; + public int Y { get; set; } = y; + } + + // Define delegate types that match the Windows Forms pattern + public delegate void KeyEventHandler(object sender, KeyEventArgs e); + public delegate void MouseEventHandler(object sender, MouseEventArgs e); + + // A simple class that demonstrates contravariance with events + public class Button + { + // Events that expect specific EventArgs-derived types + public event KeyEventHandler? KeyDown; + public event MouseEventHandler? MouseClick; + + // Method to simulate key press + public void SimulateKeyPress(string key) + { + Console.WriteLine($"Simulating key press: {key}"); + KeyDown?.Invoke(this, new KeyEventArgs(key)); + } + + // Method to simulate mouse click + public void SimulateMouseClick(int x, int y) + { + Console.WriteLine($"Simulating mouse click at ({x}, {y})"); + MouseClick?.Invoke(this, new MouseEventArgs(x, y)); + } + } + + public class Form1 + { + private Button button1; + + public Form1() + { + button1 = new Button(); + + // Event handler that accepts a parameter of the base EventArgs type. + // This method can handle events that expect more specific EventArgs-derived types + // due to contravariance in delegate parameters. + + // You can use a method that has an EventArgs parameter, + // although the KeyDown event expects the KeyEventArgs parameter. + button1.KeyDown += MultiHandler; + + // You can use the same method for an event that expects + // the MouseEventArgs parameter. + button1.MouseClick += MultiHandler; + } + + // Event handler that accepts a parameter of the base EventArgs type. + // This works for both KeyDown and MouseClick events because: + // - KeyDown expects KeyEventHandler(object sender, KeyEventArgs e) + // - MouseClick expects MouseEventHandler(object sender, MouseEventArgs e) + // - Both KeyEventArgs and MouseEventArgs derive from EventArgs + // - Contravariance allows a method with a base type parameter (EventArgs) + // to be used where a derived type parameter is expected + private void MultiHandler(object sender, EventArgs e) + { + Console.WriteLine($"MultiHandler called at: {DateTime.Now:HH:mm:ss.fff}"); + + // You can check the actual type of the event args if needed + switch (e) + { + case KeyEventArgs keyArgs: + Console.WriteLine($" - Key event: {keyArgs.KeyCode}"); + break; + case MouseEventArgs mouseArgs: + Console.WriteLine($" - Mouse event: ({mouseArgs.X}, {mouseArgs.Y})"); + break; + default: + Console.WriteLine($" - Generic event: {e.GetType().Name}"); + break; + } + } + + public void DemonstrateEvents() + { + Console.WriteLine("Demonstrating contravariance in event handlers:"); + Console.WriteLine("Same MultiHandler method handles both events!\n"); + + button1.SimulateKeyPress("Enter"); + button1.SimulateMouseClick(100, 200); + button1.SimulateKeyPress("Escape"); + button1.SimulateMouseClick(50, 75); + } + } + // + + // + // Demonstration of how contravariance works with delegates: + // + // 1. KeyDown event signature: KeyEventHandler(object sender, KeyEventArgs e) + // where KeyEventArgs derives from EventArgs + // + // 2. MouseClick event signature: MouseEventHandler(object sender, MouseEventArgs e) + // where MouseEventArgs derives from EventArgs + // + // 3. Our MultiHandler method signature: MultiHandler(object sender, EventArgs e) + // + // 4. Contravariance allows us to use MultiHandler (which expects EventArgs) + // for events that provide more specific types (KeyEventArgs, MouseEventArgs) + // because the more specific types can be safely treated as their base type. + // + // This is safe because: + // - The MultiHandler only uses members available on the base EventArgs type + // - KeyEventArgs and MouseEventArgs can be implicitly converted to EventArgs + // - The compiler knows that any EventArgs-derived type can be passed safely + // + + class Program + { + static void Main() + { + var form = new Form1(); + form.DemonstrateEvents(); + } + } +} \ No newline at end of file diff --git a/docs/csharp/programming-guide/concepts/covariance-contravariance/snippets/using-variance-in-delegates/ContravarianceExample.csproj b/docs/csharp/programming-guide/concepts/covariance-contravariance/snippets/using-variance-in-delegates/ContravarianceExample.csproj new file mode 100644 index 0000000000000..2dfe8aaebbfb1 --- /dev/null +++ b/docs/csharp/programming-guide/concepts/covariance-contravariance/snippets/using-variance-in-delegates/ContravarianceExample.csproj @@ -0,0 +1,9 @@ + + + + Exe + net9.0 + enable + + + \ No newline at end of file diff --git a/docs/csharp/programming-guide/concepts/covariance-contravariance/using-variance-in-delegates.md b/docs/csharp/programming-guide/concepts/covariance-contravariance/using-variance-in-delegates.md index b46825554d8bb..86e414362d491 100644 --- a/docs/csharp/programming-guide/concepts/covariance-contravariance/using-variance-in-delegates.md +++ b/docs/csharp/programming-guide/concepts/covariance-contravariance/using-variance-in-delegates.md @@ -51,43 +51,41 @@ class Program This example demonstrates how delegates can be used with methods that have parameters whose types are base types of the delegate signature parameter type. With contravariance, you can use one event handler instead of separate handlers. The following example makes use of two delegates: -- A delegate that defines the signature of the [Button.KeyDown](xref:System.Windows.Forms.Control.KeyDown) event. Its signature is: +- A custom `KeyEventHandler` delegate that defines the signature of a key event. Its signature is: ```csharp public delegate void KeyEventHandler(object sender, KeyEventArgs e) ``` -- A delegate that defines the signature of the [Button.MouseClick](xref:System.Windows.Forms.Control.MouseDown) event. Its signature is: +- A custom `MouseEventHandler` delegate that defines the signature of a mouse event. Its signature is: ```csharp public delegate void MouseEventHandler(object sender, MouseEventArgs e) ``` -The example defines an event handler with an parameter and uses it to handle both the `Button.KeyDown` and `Button.MouseClick` events. It can do this because is a base type of both and . +The example defines an event handler with an parameter and uses it to handle both key and mouse events. This works because is a base type of both the custom `KeyEventArgs` and `MouseEventArgs` classes defined in the example. Contravariance allows a method that accepts a base type parameter to be used for events that provide derived type parameters. + +### How contravariance works in this example + +When you subscribe to an event, the compiler checks if your event handler method is compatible with the event's delegate signature. With contravariance: + +1. The `KeyDown` event expects a method that takes `KeyEventArgs`. +1. The `MouseClick` event expects a method that takes `MouseEventArgs`. +1. Your `MultiHandler` method takes the base type `EventArgs`. +1. Since `KeyEventArgs` and `MouseEventArgs` both inherit from `EventArgs`, they can be safely passed to a method expecting `EventArgs`. +1. The compiler allows this assignment because it's safe - the `MultiHandler` can work with any `EventArgs` instance. + +This is contravariance in action: you can use a method with a "less specific" (base type) parameter where a "more specific" (derived type) parameter is expected. ### Code - -```csharp -// Event handler 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; - -} -``` + +:::code language="csharp" source="snippets/using-variance-in-delegates/ContravarianceExample.cs" id="snippet1"::: + +### Key points about contravariance + +:::code language="csharp" source="snippets/using-variance-in-delegates/ContravarianceExample.cs" id="snippet2"::: + +When you run this example, you'll see that the same `MultiHandler` method successfully handles both key and mouse events, demonstrating how contravariance enables more flexible and reusable event handling code. ## See also