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

13,345

Solution 1

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".

Solution 2

lambda is shortcut for anonymous delegate, but you will always be using delegates. the delegate specifies the methods signature. you can just do this:

 delegate(int i) { Console.WriteLine(i.ToString()) }

can be replaced with

f => Console.WriteLine(f.ToString())

Solution 3

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:

List<string> names = GetNames();
names.ForEach(Console.WriteLine);
  1. it makes code more readable thus simple to understand.
  2. It makes code shorter thus less work for us ;)

On the other hand it is very simple to misuse them. Long or/and complex lambda expressions are tending to be:

  1. Hard to understand for new developers
  2. Less object oriented
  3. Much harder to read

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.

Solution 4

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.

Solution 5

Lambda expressions are just "syntactic sugar", the compiler will generate appropriate delegates for you. You can investigate this by using Lutz Roeder's Reflector.

Share:
13,345
dragon
Author by

dragon

Updated on June 03, 2022

Comments

  • dragon
    dragon almost 2 years

    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?

  • Michael Brown
    Michael Brown over 15 years
    Actually lambda expressions are a bit more than syntactic sugar since they can be compiled into an expression tree and manipulated.
  • Shimmy Weitzhandler
    Shimmy Weitzhandler almost 15 years
    WOW!!! I never thout about this one! Is there way to do predicate too i.e. names.Where(!string.IsNullOrEmpty)); ? I tried and it doesn't work for me. Oops! If I remove the ! operand it does work, why??? I even tried puting it in parentheses but it can't invoke it altogether, is there a way? We are actually trying to convert string.IsNullOrEmpty to string.IsNotNullOrEmpty...
  • nawfal
    nawfal over 10 years
    I think the questioner is asking about delegate keyword being obsolete, in favour of newer lambda based syntax. She groups "anonymous methods and delegates" together.
  • RBT
    RBT over 7 years
    Actually I was looking for a use case since early morning today as to why would I specify an argument in a method signature but not use it in the method body :P. Event-handlers seems like an example but still 1. The omission of parameters adds to confusion. 2. Tomorrow if I fall into the need of using either of object sender, EventArgs e parameters then the developer should be aware of this specific compiler trick which isn't so obvious. For me it is a thumbs down from a feature stand-point just to save two words of typing. I strongly agree with you on - This is not a strong advantage