Reputation: 119
If Action is a delegate as stated on MDN:
public delegate void Action()
TestA (new Action (delegate { return; })); // Right.
TestA (delegate { return; }); // Wrong.
TestB (delegate { return; }); // Right.
TestB (() => { return; }); // Right.
public void TestA(Delegate del) {
// stuff...
}
public void TestB(Action callback) {
TestB (callback);
}
Upvotes: 0
Views: 910
Reputation: 203802
All delegates inherit from Delegate
, so you can pass any delegate to a method accepting a Delegate
.
Why can't an anonymous function be passed then?
Because it doesn't have a delegate type. It's an anonymous method, but the compiler doesn't know what delegate that anonymous method should be. (The use of the delegate
keyword here, when creating an anonymous method, is confusing. You're not actually creating an anonymous delegate, you're creating an anonymous method.)
The expression doesn't compile because the compiler always needs to be able to figure out what the type of any expression is, and for anonymous methods (and lambdas) it needs to do so from context. When the method is a Delegate
, it can't figure out which delegate it's supposed to be, so it fails. When you pass it to Action
, it knows what action it's supposed to be, and it's compatible, so, success.
(I read that a lambda creates an anonymous delegate as if the function was created with delegate {})
Upvotes: 2