Home >Backend Development >C++ >Why Can't Anonymous Methods Be Assigned Directly to `var` in C#?
Why Anonymous Methods Cannot Be Assigned to var
In the provided code, the assignment of the anonymous method to the var variable fails to compile due to the ambiguity in inferring the delegate type.
Anonymous methods can be assigned to delegate types, such as Func
In addition, even if the compiler could infer the delegate type, this could lead to inconsistencies. For example, assuming the var assignment compiled successfully, the following code would no longer make sense:
var comparer = delegate(string arg1, string arg2, string arg3, string arg4, string arg5) { return false; };
This is because Func<> only allows up to four arguments in .NET 3.5, so the type inference would not match the actual behavior.
To resolve this ambiguity, it is necessary to explicitly specify the delegate type when assigning anonymous methods to variables. This ensures clarity and consistency in the code.
The above is the detailed content of Why Can't Anonymous Methods Be Assigned Directly to `var` in C#?. For more information, please follow other related articles on the PHP Chinese website!