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.
public static void Invoke(Delegate d)
{
d.DynamicInvoke();
}
static void Main(string[] args)
{
// fails
Invoke(() => Console.WriteLine("Test"));
// works
Invoke(new Action(() => Console.WriteLine("Test")));
Console.ReadKey();
}
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".