How to pass an event to a method and then subscribe to it?

Posted by Ryan Peschel on Stack Overflow See other posts from Stack Overflow or by Ryan Peschel
Published on 2012-11-18T22:29:50Z Indexed on 2012/11/18 23:00 UTC
Read the original article Hit count: 283

Filed under:
|
|
|

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.

© Stack Overflow or respective owner

Related posts about c#

Related posts about events