Why anonymous method can be pass to a delegator's constructor?

Action<int, string> s = new Action<int, string>(delegate(int a,string b){});
Action<int, string> ss = delegate(int a, string b) { };

Why these both work? Why the constructor Action can accept both function and delegator?

Jon Skeet
people
quotationmark

You're not really making a constructor call in the normal way, even though that's what it looks like.

Instead, this is a delegate-creation-expression as described in the C# 5 specification, section 7.6.10.5:

A delegate-creation-expression is used to create a new instance of a delegate-type.

delegate-creation-expression:
    new   delegate-type   (   expression   )

The argument of a delegate creation expression must be a method group, an anonymous function or a value of either the compile time type dynamic or a delegate-type.

It's almost always simpler to use the implicit conversion from an anonymous function (lambda expression or anonymous method) to a compatible delegate type, which is what your second line does.

If you remember back to C# 1, this was how we had to create delegate instances, although using method groups:

Action action = new Action(SomeMethod);

C# 2 introduced anonymous methods and also the implicit conversion from method groups to delegates:

Action action = SomeMethod;

These days, delegate creation expressions are relatively rare because there are more compact ways of doing the same thing.

Note that in some cases - if you're passing the anonymous function or method group as an argument for a parameter of type Delegate, for example - you can just cast instead of using a delegate creation expression:

Foo((Action<int, string>) delegate(int a, string b) {});

people

See more on this question at Stackoverflow