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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With