views:

72

answers:

3

I can define an event like this(declared function):

MyElement.Keyup +=MyDeclaredFunction

I can also define it like this(anonymous delegate):

MyElement.Keyup+=new delegate(object sender, eventargs e) {};

I can also define it like this(lambda):

MyElement.Keyup += (sender, e) => myfunction

What is the best way to do this? One case the code for the event is found with the declaration of the event... in the other they are seperated.

I prefer method 1

can anyone tell me what the pros and cons of each method might be?

+3  A: 

Methods 2 and 3 are the same.

In method 1 you can later unsubscribe from event. In method 2 you can not unsubscribe from event. I would say this is main difference.

Alex Reitbort
Unsubscribe: not true; you can unsubscribe an anon-delegate. You can even make it self-unsubscribing. You just need to capture the delegate into a variable first. One extra line of code.
Marc Gravell
+1  A: 

The first is useful and normal for non-trivial amounts of code, or where you want to re-use code (you can do this with an anonymous method by capturing into a variable, but it loses the shine somewhat...)

The second and third are largely identical (in C# 3.0, at least), and are really handy for short blocks of code. Actually, there is a 4th option, useful if you don't care about the args:

MyElement.Keyup+= delegate { /* code */ };

Note we haven't had to declare any args (the compiler writes a compatible signature that just doesn't use them). The above trick is probably mot handy for Click events (I'm guessing that for KeyUp you are interested in which key was pressed, so probably don't use this one in your scenario).

Marc Gravell
+1  A: 

I prefer to use the attach/detach pattern when attaching to events whenever I know that I will need to unsubscribe from an event at some later point in my code.

Using labdas and anonymous methods do not allow us to do this unless we assign the anonymous methods or lambdas to delegate variables.

I would say the one pro of using decalration in (1) is that the method will be declared elsewhere within your class and this makes it easy for a developer to "scan" your code and discover the event handlers methods, whereas the anonymous methods and lambdas can be declared right where they are needed and it might not be obvious without reading the method's code that declares them.

Mike J