This question already has an answer here:
If I have a lambda such as () => { throw new Exception(); }
, it's unclear whether it has a return type or not. Because of this, it can be (implicitly) converted to both Action
and Func<object>
(or any other Func<T>
). This is because, according to §6.5 Anonymous function conversions of the C# 4 spec:
[A] delegate type
D
is compatible with an anonymous functionF
provided:
…
If
D
has avoid
return type and the body ofF
is a statement block, when […] the body ofF
is a valid statement block in which no return statement specifies an expression.If
D
has a non-void return type and the body ofF
is a statement block, when […] the body ofF
is a valid statement block with a non-reachable end point in which eachreturn
statement specifies an expression that is implicitly convertible to the return type ofD
.
But if I have two overloads of a method, where one has a parameter of type Action
and the other Func<object>
, and I pass it the lambda from above, the Func<object>
overload is used. Why? Which part of specification says that Func<object>
is better than Action
in this case?
I have looked at §7.5.3.2 Better function member, but that does not explain it.
I should've looked one section lower: §7.5.3.3 Better conversion from expression explains that: