ReSharper 2024.3 Help

Code inspection: Convert lambda expression into 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.

ReSharper 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: 08 April 2024