views:

60

answers:

2

I've recently discovered this technique in my ASP.NET code base that I maintain. What does it do and how would I use it? And Maybe more importantly, would this work at all given ASP.NET is using simulated-page-life-cycle-events?

    public event EventHandler CancelEvent
    {
        add { cancelButton.Click += value; }
        remove { cancelButton.Click -= value; }
    }

Resharper says the event is currently unused and I've never seen this technique before. Usually I wire up my events on OnInit.. eg.

    cancelButton.Click += HandleClick;
+3  A: 

It's just delegating the event handling basically - when someone subscribes to your CancelEvent event, it's just adding that event handler to the cancelButton's Click event, and likewise for removal.

It means that your type is exposing an event representing cancellation instead of just exposing the button itself. Of course, if nothing else wants to use that event, it's pointless in this case - but it's an interesting technique to know about.

Jon Skeet
Beat by SkeetBot yet again...Argh.
Justin Niessner
Resistance is futile... the SkeetBot answers all
Dave Swersky
A: 

This is the way to expose event properties for user controls. In the asp.net mark-up, you would use something similar to the code below:

<my:control id="cancelbutton" OnCancelEvent="myCancelEventHandler" ... </my:control>

This is mostly used when extending web controls or creating composite controls and you want the handlers to be defined on the mark-up not in the code.

0zkar