Exposing Hidden Events

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
{
add{
this.hiddenControl.MyEvent += value;
}

remove{
this.hiddenControl.MyEvent -= value;

}
}

Now you can subscribe to the event in MainForm without making the usercontrol member public in ControlPanel.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: