What's the benefits of registering an event handler implicitly

Go To StackoverFlow.com

1

What's the benefits of registering an event as:

void MyMethod()
{
    button1.Click += delegate (object sender, EventArgs e)
    {
        ..
    }
}

in comparison with:

void MyMethod()
{
    button1.Click += new System.EventHandler(this.button1_Click);
}

void button1_Click(object sender, EventArgs e)
{
    ..
}

UPDATE: And what about unsubscribing it?

2012-04-04 06:35
by Mimi


2

The benefit is that you don't have to come up with a name and a place in your class.

For a light function, tightly coupled to the code that register the event, the short version is more convenient.

Note that you can also exchange delegate for a =>

button1.Click += (object sender, EventArgs e) =>   
{
    ..
}
2012-04-04 06:42
by Henk Holterman
And what about unregistering it - Mimi 2012-04-04 06:48
If you ever have to unregister it (most handlers don't need to) then that's a good reason to use a named method - Henk Holterman 2012-04-04 06:51
I found the way here ; - Mimi 2012-04-08 05:16


3

You can be even more concise:

button1.Click += ( sender, e ) =>
{
};

Syntactically it's cleaner (as long as it doesn't lead to long blocks of code which would be better broken up into named methods).

The inline declaration is a closure, which gives you access to the variables adjacent to the anonymous method.

From: What are 'closures' in .NET?

In essence, a closure is a block of code which can be executed at a later time, but which maintains the environment in which it was first created - i.e. it can still use the local variables etc of the method which created it, even after that method has finished executing.

See also: http://csharpindepth.com/articles/chapter5/closures.aspx

2012-04-04 06:42
by Tim Medora


2

When registering event handler with an anonymous delegate or lambda, you can write shorter code and use closures. But you cannot unsubscribe from the event, and if the event handler code is too long, your code becomes ugly.

2012-04-04 06:45
by Dennis


1

It's just about coding style.

Worth mantioning that declaring it like in first case let you to avoid "spaghetti code" and inject into the handler function local variables (if needed) in more natural(human readable way).

To be more clear. By writing like in first case you can:

int x = 0; 

System.Windows.Forms.Button button = new System.Windows.Forms.Button(); 
button.Click += (o,e)=> {   
++x; 
};

Inside the event handler you can access the local variable declared actually out for the scope of the handler method. For most people it seems "natural", but if you think like a developer it shouldn't be even possible.

Good luck.

2012-04-04 06:42
by Tigran
Ads