I’m trying to write a extension method of EventHandler, as followed:
public static class MyExtensions
{
public static void Add(this EventHandler handler, EventHandler next)
{
//Do something
}
}
It works fine for my events, such as:
public event EventHandler MyEvent
I can use my extension with no problem:
MyEvent.Add((x, y) => { /* do something */ });
But when I want to apply it to Click event of a TextBox, I get a compilation error:
error CS0079:
The event System.Windows.Forms.TextBoxBase.Click can only appear on the left hand side of
+=or-=
What puzzle me is, the Click event doesn’t look any different from MyEvent, so why it does have the constraint?
If the
Addmethod is called from within the same class thatMyEventis defined it’d probably work just fine.However, the
Clickmethod is defined in a different class than where you are callingAddfrom. That’s why it doesn’t work.The .NET framework doesn’t allow events to be directly modified outside of the class that defined it otherwise a bit of rouge code could remove all of the event handlers of any class.
Here’s the best extension method that I could come up with that will help you do what you want:
You can use it like this:
The
cleanupaction is used to remove the event handler when it is not needed.I left out all of the required null-check code for simplicity. You would have to put them in in the appropriate places.