SA1130: Use lambda syntax
📝 This rule is new for StyleCop Analyzers, and was not present in StyleCop Classic.
Cause
An anonymous method was declared using the form delegate (parameters) { }, when a lambda expression would provide
equivalent behavior with the syntax (parameters) => { }.
Rule description
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; };
Action d = static delegate() { z = 0; };
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;
Action d = static () => { z = 0; };
📝 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;
}
How to fix violations
To fix a violation of this rule, replace the anonymous function with an equivalent lambda expression.
The code fix keeps the anonymous method's parameter names. It also keeps the parameter types where the lambda needs them:
for ref, out and in parameters, when a generic method infers its type arguments from them, when the anonymous
method isn't converted to a delegate type, and when removing them would make an overloaded call ambiguous.
How to suppress violations
#pragma warning disable SA1130 // Use lambda syntax
Action a = delegate { x = 0; };
#pragma warning restore SA1130 // Use lambda syntax