Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

method subscription vs lambda delegate subscription - Which and why?

I have seen some people leaning on handing methods to callbacks/events and then sometimes just handing them lambdas.

Can anybody speak to any difference between the two? I would have originally thought them to be the same, but the inconsistency I have seen implemented sometimes makes me wonder if there is a case where one is preferable over the other? Obviously if there is a very large ammount of code it shouldn't be an on the spot lambda, but otherwise..

Can you all outline any differences between the two if any, and outline the rules you use in choosing between the two when both are available?

like image 650
Jimmy Hoffa Avatar asked Aug 31 '10 15:08

Jimmy Hoffa


People also ask

What is the difference lambdas and delegates?

They are actually two very different things. "Delegate" is actually the name for a variable that holds a reference to a method or a lambda, and a lambda is a method without a permanent name. Lambdas are very much like other methods, except for a couple subtle differences.

Is a lambda expression a delegate?

Lambda expressions are also examples of delegates, which are collections of lines of code that can take inputs and optionally return outputs. We use the type Func<T> to define delegates that return an output, and Action<T> for delegates that will not return an output.

Can you provide a concise distinction between anonymous method and lambda expressions?

Anonymous Method is an inline code that can be used wherever a delegate type is expected. Microsoft introduced Anonymous Methods in C# 2.0 somewhere around 2003. Lambda expression is an anonymous method that you can use to create delegates or expression tree types.

What is delegate in LINQ?

Introduction. A delegate is a C# type similar to function pointers in C++. It encapsulates references to one or multiple methods. Func<> is a special kind of Multicast Delegate used frequently with LINQ and Enumerable extensions. Let's have a close look at Func<> delegates.


1 Answers

One of the biggest differences between the two is the ease by which you can unsubscribe from the event. With the method based approach unsubscribing is a simple operation, simply use the original method

m_button.Click += OnButtonClick; 
...
m_button.Click -= OnButtonClick;

With lambdas this is not as simple. You must store away the lambda expression and to be used later on to unsbuscribe from the event

m_button.Click += delegate { Console.Write("here"); }
...
// Fail
m_button.Click -= delegate { Console.Write("here"); } 

EventHandler del = delegate { Console.Write("here"); }
m_button.Click += del;
...
m_button.Click -= del;

It really detracts from the convenience of using lambda expressions.

like image 194
JaredPar Avatar answered Sep 21 '22 07:09

JaredPar