Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning anonymous method to delegate using parentheses gives compiler error?

Given the following sample codes:

static void SomeMethod()
{
  Action<int,int> myDelegate;

  //...

  myDelegate = delegate { Console.WriteLine( 0 ); };
  myDelegate = delegate() { Console.WriteLine( 0 ); };  // compile error

}

What is the difference between

myDelegate = delegate { Console.WriteLine( 0 ); };

and

myDelegate = delegate() { Console.WriteLine( 0 ); };

?

In this example, the second statement generates compile error while the first one does not.

like image 904
Setyo N Avatar asked Apr 19 '12 04:04

Setyo N


People also ask

What is an anonymous function that can be used to create delegates or expression types called?

Lambda expressions A Lambda expression is an anonymous function that can contain expressions and statements. They are also used to create delegates or expression tree types. Expressions can be mystifying, but simply put, they are nothing more than code represented as data and objects in a . NET application.

What is anonymous delegate in C#?

Anonymous methods provide a technique to pass a code block as a delegate parameter. Anonymous methods are the methods without a name, just the body. You need not specify the return type in an anonymous method; it is inferred from the return statement inside the method body.


1 Answers

An anonymous method has the syntax delegate parameter-list { statement-list }. The parameter list is optional.

If you omit the parameter list then the anonymous method is compatible with any delegate type where the parameters are not marked "out".

If you supply the parameter list then it must match the delegate parameter types exactly.

In your first case you are omitting it, and in the second case you are supplying it but not matching the delegate parameters. So delegate {} is legal, and delegate (int i, int j) { } is legal, but delegate () {} is not.

In any event, you are probably better off using a lambda expression; it is the more common syntax in new code: (i, j)=>{ };

like image 196
Eric Lippert Avatar answered Nov 03 '22 03:11

Eric Lippert