In these delegates:
EventHandler
public delegate void EventHandler(object sender, EventArgs e);
FormClosingEventHandler
public delegate void FormClosingEventHandler(object sender, FormClosingEventArgs e);
FormClosingEventArgs is inherited from EventArgs. Why can’t I bind an FormClosing event with an event handler from EventHandler delegate?
I know that the event handler’s signiture must match its delegate, but why it doesn’t suppot matching inherited types ?
Well, it’s interesting…
You can bind an eventhandler using a method group conversion with compatible types:
This will actually create an instance of
FormClosingEventHandler, notEventHandler.However you can’t subscribe directly with an existing delegate of type EventHandler:
… but you can create a new delegate based on an existing one, if the types are compatible:
Basically you need to remember that all the syntactic sugar is effectively calling a method like this:
where the method has a signature of:
Now remember that although they have compatible signatures, there’s no reference conversion available from
EventHandlertoFormClosingHandler. It’s not like one inherits from the other.It gets even more confusing with generic covariance/contravariance, but we’ll leave it there for now… hopefully that’s given you something to chew on and options for working round the restrictions.