Question

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.

Was it helpful?

Solution

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)=>{ };

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top