Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can anonymous delegates omit arguments, but lambdas can't?

//ok
Action<int> CallbackWithParam1 = delegate { };    

//error CS1593: Delegate 'System.Action<int>' does not take 0 arguments
Action<int> CallbackWithParam2 = () => { };   

Just wondered why the discrepancy really. :-/

like image 531
GazTheDestroyer Avatar asked Feb 16 '12 16:02

GazTheDestroyer


People also ask

What is the difference between lambda expression and anonymous methods?

Anonymous methods are basically functions without a name, with the ability to create closures. Lambda expressions are constructs that are convertible to both anonymous methods and expression trees, and follow more complex rules of type inference than anonymous methods.

How are an anonymous delegate and a lambda expression related?

Anonymous Method is an inline code that can be used wherever a delegate type is expected. Microsoft introduced Anonymous Methods in C# 2.0 somewhere around 2003. Lambda expression is an anonymous method that you can use to create delegates or expression tree types.

What is the difference between lambdas and delegates?

They are actually two very different things. "Delegate" is actually the name for a variable that holds a reference to a method or a lambda, and a lambda is a method without a permanent name. Lambdas are very much like other methods, except for a couple subtle differences.

Is a lambda expression a delegate?

Since a lambda expression is just another way of specifying a delegate, we should be able to rewrite the above sample to use a lambda expression instead of an anonymous delegate. In the preceding example, the lambda expression used is i => i % 2 == 0 . Again, it is just a convenient syntax for using delegates.


1 Answers

Jared is of course correct. To add a couple more details:

  • Almost no one uses the "skip the parameter list" syntax.
  • We have no scenario for lambdas that requires that feature.
  • The feature complicates type inference and overload resolution, and makes it more likely that both will fail.
  • What syntax would you like for the feature? Action<int> c = => {}; ??? I have no desire whatsoever to make => into a unary prefix operator.

So on the one hand we have the list of pros:

  • Lambdas gain consistency with an unnecessary C# 2.0 feature that hardly anyone knows about or uses -- a feature that frankly, we wish we'd never done in the first place

and the cons:

  • implementation complicates already-complex type inference and overload resolution algorithms
  • feature leads to more bug possibilities for users with no corresponding gain in representational power.
  • no obviously nice syntax

If you were given that list of pros and cons, what would you do? I hope "implement the feature" would not be your choice; it was not ours.

like image 64
Eric Lippert Avatar answered Sep 20 '22 09:09

Eric Lippert