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?
Yes there are places where directly using anonymous delegates and lambda expressions won't work.
If a method takes an untyped Delegate then the compiler doesn't know what to resolve the anonymous delegate/lambda expression to and you will get a compiler error.
The failing line of code will get the compiler error "Cannot convert lambda expression to type 'System.Delegate' because it is not a delegate type".
Lambda expressions are just "syntactic sugar", the compiler will generate appropriate delegates for you. You can investigate this by using Lutz Roeder's Reflector.
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 msdnFor example you can do:
While this fails:
This technique mostly comes handy when writing event-handlers, like:
This is not a strong advantage. It's better to adopt the newer syntax always imho.
Lambda expression is not (and was not meant to be) a silver bullet that would replace (hide) delegates. It is great with small local things like:
On the other hand it is very simple to misuse them. Long or/and complex lambda expressions are tending to be:
So “does it mean we don’t have to use delegates or anonymous methods anymore?” No – use Lambda expression where you win time/readability otherwise consider using delegates.
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.lambda is shortcut for anonymous delegate, but you will always be using delegates. the delegate specifies the methods signature. you can just do this:
can be replaced with