Lambda expression warnings - C# reference (original) (raw)

There are several errors related to declaring and using lambda expressions:

In addition, there are several warnings related to declaring and using lambda expressions:

Syntax limitations in lambda expressions

Some C# syntax is prohibited in lambda expressions and anonymous methods. Using invalid constructs in a lambda expression causes the following errors:

All the following constructs are disallowed in lambda expressions:

You can't use any of these constructs in a lambda expression or an anonymous method. Many are allowed in a local function.

In addition, interpolated string handler types are ignored when applied to a lambda parameter. If you use one, you see the following warning:

Lambda expression parameters and returns

These errors indicate a problem with a parameter declaration:

Lambda expression parameters must follow these rules:

Return types of lambda expression must follow these rules:

Lambda expression delegate type

When you declare a default value or add the params modifier with a lambda expression parameter, the delegate type isn't one of the Func or Action types. Rather, it's a custom type that includes the default parameter value or params modifier. The following code generates warnings because it assigns a lambda expression that has a default parameter to an Action type:

Action<int> a1 = (int i = 2) => { };
Action<string[]> a3 = (params string[] s) => { };

To fix the error, either remove the default parameter or use an implicitly typed variable for the delegate type:

Action<int> a1 = (int i) => { };
var a2 = (int i = 2) => { };
Action<string[]> a3 = (string[] s) => { };
var a4 = (params string[] s) => { };