Instead of passing an anonymous method to a delegate, or using a statement lambda, you can use a lambda expression. This is true only for methods containing a single statement.
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.
tip
If the resulting lambda expression contains different statements on the same line, you can set breakpoints on the statement where your caret is by pressing F9 (not by clicking in the left margin).
In the example below, ReSharper suggests assigning a lambda expression to the sum delegate instead of using a longer anonymous method:
Suboptimal code
classMyClass
{
publicstaticintMyMethod()
{
Func<int,int,int> sum =
delegate(int x,int y)
{
return x + y;
};
returnsum(10,20);
}
}
After the quick-fix
classMyClass
{
publicstaticintMyMethod()
{
Func<int,int,int> sum =
(x, y)=> x + y;
returnsum(10,20);
}
}
In the following example, ReSharper suggests converting a statement lambda to a lambda expression:
Suboptimal code
classMyClass1
{
publicstaticintMyMethod()
{
Func<int,int,int> sum =
(x, y)=>
{
return x + y;
};
returnsum(10,20);
}
}
After the quick-fix
classMyClass1
{
publicstaticintMyMethod()
{
Func<int,int,int> sum =
(x, y)=> x + y;
returnsum(10,20);
}
}
tip
Reverse transformation is available with a context actionAltEnter.
Our website uses some cookies and records your IP address for the purposes of accessibility, security, and managing your access to the telecommunication network. You can disable data collection and cookies by changing your browser settings, but it may affect how this website functions. Learn more.
With your consent, JetBrains may also use cookies and your IP address to collect individual statistics and provide you with personalized offers and ads subject to the Privacy Notice and the Terms of Use. JetBrains may use third-party services for this purpose. You can adjust or withdraw your consent at any time by visiting the Opt-Out page.