Question

static void HandleDemoEvent(object sender, EventArgs e)
{
    Console.WriteLine("bla-bla");
}

static void Main(string[] args)
{
    EventHandler handler;
    MouseEventHandler mouseHandler;

    handler = HandleDemoEvent; //Line#1 - Compile OK
    mouseHandler = HandleDemoEvent; //Line#2 - Compile OK
    mouseHandler = handler; //Line#3 Compile Error  1   Cannot implicitly convert type 'System.EventHandler' to 'System.Windows.Forms.MouseEventHandler'

}

Both EventHandler delegate type and my own HandleDemoEvent method have the same method signature. Yet Line#2 compiles fine (contravariance at play), but Line#3 fails with failed implicit typecast error. A simple example, and I intuitively understand why the compile error is taking place for Line#3, but I can't settle it in my mind with some kind of formal explanation. Can anybody please come up with a good understanding to explain the difference?

Was it helpful?

Solution

Delegate co-/contravariance only works for when you're building a delegate from a method, as in your first two cases.

It doesn't work for when you're assigning one delegate to another, as in your last case. (Unless you use generic delgates, in which case you can use co-/contravariance on the generic parameters.)

An EventHandler isn't a MouseEventHandler - but both can wrap a void method taking an object and an EventArgs.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top