JetBrains Rider 2022.2 Help

Code Inspection: Convert lambda expression to method group

With respect to delegates, method groups provide a simple syntax to assign a method to a delegate variable. This syntax does not require explicitly invoking the delegate's constructor. Method groups allow using overloads of the method. Which overload to invoke is determined by the delegate’s signature.

If an anonymous function (expression lambda or anonymous method) consists of only one method, it is possible to convert it to a method group to achieve more compact syntax and prevent compile-time overhead caused by using lambdas. The links in See Also below provide details about general difference between lambda expressions and method groups. After compilation, there also might be a difference in terms of performance, but it largely depends on the scenario — see this comment on StackOverflow.

JetBrains Rider suggests a quick-fix that replaces the lambda expression with a method group Console.WriteLine.

internal static class DelegateTest { private delegate void MethodDelegate(string message); public void Main(string[] args) { MethodDelegate mymethod = message => { Console.WriteLine(message); }; mymethod("test"); Console.ReadLine(); } }
internal static class DelegateTest { private delegate void MethodDelegate(string message); public void Main(string[] args) { MethodDelegate mymethod = Console.WriteLine; mymethod("test"); Console.ReadLine(); } }

The next example shows this quick-fix applied to an anonymous method:

internal class DelegateTest { private delegate void MethodDelegate(string message); public static void Main(string[] args) { MethodDelegate mymethod = delegate(string message) { Console.WriteLine(message); }; mymethod("test"); Console.ReadLine(); } }
internal class DelegateTest { private delegate void MethodDelegate(string message); public static void Main(string[] args) { MethodDelegate mymethod = Console.WriteLine; mymethod("test"); Console.ReadLine(); } }
Last modified: 29 April 2021