Exposing Hidden Events
April 1, 2008 Leave a comment
I found this small little note while surfing for my requirements … adding it to my blog so everybody can benefit.
I recently ran into a neat little nugget of functionality in C# with events. Normally in C# when we define events we stop at something like this:public event EventHandler MyEvent;
The thing is, you can explicitly implement the add and remove accessors if you throw some curly braces into the mix. Why does this matter? Imagine that you have a MainForm, and a usercontrol named ControlPanel. ControlPanel contains another usercontrol called hiddenControl that exposes an event that you want to handle in MainForm, but all MainForm has access to is ControlPanel…
public event EventHandler MyEvent
this.hiddenControl.MyEvent += value;
this.hiddenControl.MyEvent -= value;
Now you can subscribe to the event in MainForm without making the usercontrol member public in ControlPanel.