1

Given a func that takes N parameters, why is it possible to assign a delegate to it that doesn't explicitly declare any parameters? e.g.

Func<int, string, object, string, bool> test;
// (1) this makes sense to me
test= delegate (int a, string b, object c, string d) { return true; };

// (2) this also makes sense to me
test= (a,b,c,d)=>true; 

// (3) why does this work? 
test = delegate { return true; }; 

Why does (3) work? Is there any difference between (1), (2), and (3)? Can we access the parameters from inside the braces of the third variation?

Anonymous
  • 739
  • 7
  • 15
  • 1
    Anonymous methods are flexible, useful to write an event handler inline that just doesn't need the passed arguments. Doesn't get used much anymore, most programmer opt for a lambda expression today. The C# compiler can easily generate the correct code, it knows what concrete method it needs to generate from the delegate signature. – Hans Passant Feb 15 '18 at 17:08

1 Answers1

3

Why does (3) work?

From the C# programming guide on MSDN:

Anonymous methods enable you to omit the parameter list. This means that an anonymous method can be converted to delegates with a variety of signatures


Is there any difference between (1), (2), and (3)?

delegate keyword vs. lambda notation

Can we access the parameters from inside the braces of the third variation?

No. Don't omit the parameter list if you intend to use the parameters in your anonymous method.

mm8
  • 163,881
  • 10
  • 57
  • 88