Assigning an anonymous method to delegation using brackets gives a compiler error?

Given the following code examples:

static void SomeMethod() { Action<int,int> myDelegate; //... myDelegate = delegate { Console.WriteLine( 0 ); }; myDelegate = delegate() { Console.WriteLine( 0 ); }; // compile error } 

What's the difference between

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

and

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

?

In this example, the second statement generates a compilation error, but the first does not.

+9
c # anonymous-methods delegates
source share
1 answer

The anonymous method has a list of syntax delegate { operator-list } parameters. The parameter list is optional.

If you omit the parameter list, the anonymous method will be compatible with any type of delegate where the parameters are not marked as "out".

If you provide a list of parameters, then it must exactly match the types of delegate parameters.

In the first case, you omit it, and in the second case, you provide it, but it does not match the delegate settings. Thus, delegate {} valid, but delegate (int i, int j) { } valid, but delegate() {} is not.

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

+22
source share

All Articles