Event Handler
public void DeliverEvent(object sender, EventArgs e)
{
}
#1: This Works
public void StartListening(Button source)
{
source.Click += DeliverEvent;
}
#2: And so does this..
public void StartListening(EventHandler eventHandler)
{
eventHandler += DeliverEvent;
}
But in #2, you cannot call the method because if you try something like this:
StartListening(button.Click);
You get this error:
The event 'System.Windows.Forms.Control.Click' can only appear on the left hand side of += or -=
Is there any way around that error? I want to be able to pass the event and not the object housing the event to the StartListening method.
You are mixing events with delegates. You should probably read this article by Jon Skeet which will explain the differences between the two.
The reason the second option doesn’t work is because the method expects a parameter that is a delegate that conforms to the
EventHandlersignature.Button.Clickrefers to an event rather than a delegate. Events just encapsulate delegates.I’m not sure what you are trying can be done. Conceptually what you want to do doesn’t actually make sense; it is the logic of the handler you want to pass around not the event itself.
Take a look at this post which looks at some ways of simulating the effect you want.