Is one syntax the best choice for anonymous handlers?

That is all I know for handling the event. Any other syntax is just a scope game.

// one Button.Click += delegate { /* do something */ }; // two Button.Click += delegate(object s, EventArgs e) { /* do something */ }; // three RoutedEventHandler handler = (s, e) => { /* do something */ }; Button.Click += handler; Button.Click -= handler; // four Button.Click += (s, e) => { /* do something */ }; 

I understand that the numbers one / two are basically the same, with the exception of explicit arguments that can be used in the resulting logic. I also understand that the number three allows me to add a handler and remove it, which can be very important. And, I understand, the number four is a simplified version of the second number.

My question is more practical. Between these two syntaxes, are there any reasons to use one above the other, or are they basically two ways to do the same thing? And how do you know?

 // two Button.Click += delegate(object s, EventArgs e) { /* do something */ }; // four Button.Click += (s, e) => { /* do something */ }; 
+4
source share
1 answer

Between these two syntaxes, is there any reason to use one over the other, or are they basically two ways to do the same thing?

They effectively do the same. In both cases, the compiler generates an anonymous method for you, creates a delegate and assigns it. The main advantage of the new lambda syntax is that it is shorter. An anonymous documentation method instead suggests instead of lambda syntax (syntax four):

C # 2.0 introduces anonymous methods, and in C # 3.0 and later versions, lambda expressions replace anonymous methods as the preferred way to write inline code.

Note that the syntax of the anonymous method (using delegate ) has another function not found in the lambda syntax. If you are not going to use the arguments, you can leave them and write:

 Button.Click += delegate { /* do something */ }; 

At the same time, Lambda Expressions (syntax 4) supports an additional function by anonymous methods, including improved typing of implicity, using the same syntax to create expression trees and asynchronous lambda support for C # 5.

+4
source

Source: https://habr.com/ru/post/1486664/


All Articles