In C#, anonymous methods provide a convenient way to define inline functions. While these methods can be easily assigned to delegate types, attempting to assign them to implicitly-typed variables (using var) often leads to compiler errors.
Consider the following code sample:
Func<string, bool> comparer = delegate(string value) { return value != "0"; };
This code successfully compiles, as the anonymous method is explicitly assigned to a Func
var comparer = delegate(string value) { return value != "0"; };
Error:
Cannot assign anonymous method to an implicitly-typed local variable.
This error occurs because the compiler cannot infer the type of the anonymous method. There are an infinite number of possible delegate types it could represent, including Func, Predicate, Action, and countless others.
Additionally, even if the compiler inferred Func
var comparer = delegate(string arg1, string arg2, string arg3, string arg4, string arg5) { return false; };
However, this does not make sense because Func
To resolve this issue and ensure that the anonymous method is compiled to the correct delegate type, it is necessary to explicitly specify the delegate type in the assignment statement, as seen in the first code sample.
The above is the detailed content of Why Can't I Assign Anonymous Methods to `var` in C#?. For more information, please follow other related articles on the PHP Chinese website!