Why Can't Anonymous Methods Be Assigned to Variables Inferred to the Implicit Type 'Var'?
Consider the following code:
Func<string, bool> comparer = delegate(string value) { return value != "0"; };
This code compiles successfully because the inferred type of the lambda expression is a Func delegate. However, the following code does not compile:
var comparer = delegate(string value) { return value != "0"; };
The compiler cannot infer the delegate type for the lambda expression in this case. This is because there are infinitely many possible delegate types that could be inferred, and the compiler does not have enough context to determine which one is intended.
For example, the lambda expression could be of type Func
To resolve this issue, explicitly specify the delegate type for the lambda expression:
var comparer = (Func<string, bool>)delegate(string value) { return value != "0"; };
With this change, the code will compile successfully, and the inferred type of the lambda expression will be Func
The above is the detailed content of Why Can't Implicitly Typed Variables ('var') Hold Anonymous Methods Without Explicit Type Declaration?. For more information, please follow other related articles on the PHP Chinese website!