ReSharper 2017.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 in question. 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 article and this comment.

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

Suboptimal codeAfter the quick-fix
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:

Suboptimal codeAfter the quick-fix
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: 11 December 2017

See Also