Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a case where delegate syntax is preferred over lambda expression for anonymous methods?

With the advent of new features like lambda expressions (inline code), does it mean we dont have to use delegates or anonymous methods anymore? In almost all the samples I have seen, it is for rewriting using the new syntax.

Any place where we still have to use delegates and lambda expressions won't work?

like image 982
dragon Avatar asked Sep 19 '08 23:09

dragon


2 Answers

One not so big advantage for the older delegate syntax is that you need not specify the parameters if you dont use it in the method body. From msdn

There is one case in which an anonymous method provides functionality not found in lambda expressions. Anonymous methods enable you to omit the parameter list. This means that an anonymous method can be converted to delegates with a variety of signatures. This is not possible with lambda expressions.

For example you can do:

Action<int> a = delegate { }; //takes 1 argument, but not specified on the RHS

While this fails:

Action<int> a = => { }; //omitted parameter, doesnt compile.

This technique mostly comes handy when writing event-handlers, like:

button.onClicked += delegate { Console.WriteLine("clicked"); };

This is not a strong advantage. It's better to adopt the newer syntax always imho.

like image 199
nawfal Avatar answered Oct 02 '22 12:10

nawfal


Delegate have two meanings in C#.

The keyword delegate can be used to define a function signature type. This is usually used when defininge the signature of higher-order functions, i.e. functions that take other functions as arguments. This use of delegate is still relevant.

The delegate keyword can also be used to define an inline anonymous function. In the case where the function is just a single expression, the lambda syntax is a simpler alternative.

like image 35
JacquesB Avatar answered Oct 02 '22 12:10

JacquesB