ReSharper 2017.1 Help

Code Inspection: Convert to lambda expression

Instead of passing an anonymous method with a single statement to a delegate, or using a statement lambda with a single statement, you can use a lambda expression. Both lambda expressions and anonymous methods can be used to create anonymous functions but lambda expressions provide a shorter syntax for that.

There are some minor differences between using these two notations — use the links in the See Also section below to learn the details.

In the example below, ReSharper suggests assigning a lambda expression to the sum delegate instead of using a longer anonymous method:

Suboptimal codeAfter the quick-fix
class MyClass { public static int MyMethod() { Func<int, int, int> sum = delegate(int x, int y) { return x + y; }; return sum(10, 20); } }
class MyClass { public static int MyMethod() { Func<int, int, int> sum = (x, y) => x + y; return sum(10, 20); } }

In the following example, ReSharper suggests converting a statement lambda to a lambda expression:

Suboptimal codeAfter the quick-fix
class MyClass1 { public static int MyMethod() { Func<int, int, int> sum = (x, y) => { return x + y; }; return sum(10, 20); } }
class MyClass1 { public static int MyMethod() { Func<int, int, int> sum = (x, y) => x + y; return sum(10, 20); } }
Last modified: 12 October 2017

See Also