views:

69

answers:

3

I've done some reading on SO, but didn't find the answer to my question.

As @Canavar points out in his answer there are 2 ways to subscribe to an event:

Declarative:

<asp:Button runat="server" ID="myButton" OnClick="myButton_Click" />

Code Behind:

myButton.Click += new EventHandler(myButton_Click);

I subscribe to events declaratively, but hardly ever use the "sender" and EventArgs in default event handlers. Most of the time I end up calling a method from the event handler.

Would it be better to subscribe to events using a delegate?

myButton.Click += delegate{DoStuff();};

Let me know if I'm over complicating things, and should stick to declarative event subscription, and calling my DoStuff() method from default event handler.

+3  A: 

Your handler needs to match the event's specified params. If you use a delegate you will just be defining the same thing. Discarding the params seems like a waste since you might need them in the future for some reason. I can't think of any good reason to not want the parameters.

And an event handler is a delegate already :)

Kelsey
that's the thing - the parameters don't have to match. myButton.Click += delegate{DoStuff();}; works just fine
roman m
Interesting I didnt know that. But either way you are not gaining anything by doing it with an anonymous delegate except discarding information (provided by the params), that could be needed later. I see no advantage pluses.
Kelsey
+2  A: 

I personally use the declarative approach whenever possible. While neither the declarative nor imperative approach is really "better" than the other, both have their merits. For the most part, using the declarative approach means you have greater decoupling and more flexibility between page behavior and page content. If you, for whatever reason, need to change you're page content around, using the declarative approach gives you more leeway to do so without requiring a recompile.

That does not mean the imperative approach is useless. There are times when it is not possible to apply handlers declaratively. Namely dynamic scenarios. The imperative approach allows you to use code to create dynamic content and still wire up events. Use what fits the scenario best. There is no one proper approach, both have their niche.

jrista
A: 

My favorite:

myButton.Click += myButton_Click;

The EventHandler is not actually needed. Also, if you are C# 3.0, you can go lambda on it:

myButton.Click += (x,a)=>DoStuff();  // something like that.

But really, it isn't worth worrying about too much.

Chris Brandsma