TypeName | SA1130UseLambdaSyntax |
CheckId | SA1130 |
Category | Readability Rules |
📝 This rule is new for StyleCop Analyzers, and was not present in StyleCop Classic.
An anonymous method was declared using the form delegate (parameters) { }
, when a lambda expression would provide
equivalent behavior with the syntax (parameters) => { }
.
A violation of this rule occurs whenever the code contains an anonymous method using the "old" style
delegate (parameters) { }
.
For example, each of the following would produce a violation of this rule:
Action a = delegate { x = 0; };
Action b = delegate() { y = 0; };
Func<int, int, int> c = delegate(int m, int n) { return m + n; };
The following code shows the equivalent variable declarations using the more familiar lambda syntax.
Action a = () => { x = 0; };
Action b = () => { y = 0; };
Func<int, int, int> c = (m, n) => m + n;
📝 It is not always possible to replace an anonymous method with an equivalent lambda expression. For example, the following code would not produce any violations of this rule, because the anonymous method and lambda expression have different semantics.
var x = A(() => { }); // Expression
var y = A(delegate { }); // Action
private Expression<Action> A(Expression<Action> expression)
{
return expression;
}
private Action A(Action action)
{
return action;
}
To fix a violation of this rule, replace the anonymous function with an equivalent lambda expression.
#pragma warning disable SA1130 // Use lambda syntax
Action a = delegate { x = 0; };
#pragma warning restore SA1130 // Use lambda syntax