Home >Backend Development >C++ >Why Can't I Assign an Anonymous Method to a `var` Variable in C#?
Why Anonymous Method Cannot Assign to Var
When encountering an anonymous method like:
delegate(string value) { return value != "0"; }
The compiler is faced with a challenge. Unlike a typed lambda expression such as:
Funccomparer = delegate(string value) { return value != "0"; };
The anonymous method doesn't explicitly specify a delegate type. The compiler must infer that type based on the method's signature. However, there are infinite potential delegate types that satisfy these conditions, with varying parameters and return values.
Inferring the type for an anonymous method presents several issues:
Therefore, the compiler error "Cannot assign anonymous method to an implicitly-typed local variable" prevents the use of var with anonymous methods.
The above is the detailed content of Why Can't I Assign an Anonymous Method to a `var` Variable in C#?. For more information, please follow other related articles on the PHP Chinese website!