Code inspection: Convert lambda expression into method group
Category: Language Usage Opportunities
ID: ConvertClosureToMethodGroup
EditorConfig: resharper_convert_closure_to_method_group_highlighting=[error|warning|suggestion|hint|none]
Language: C#
Requires SWA: No
tip
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
.
Suboptimal code
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(); }}
After the quick-fix
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 code
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(); }}
After the quick-fix
internal class DelegateTest{ private delegate void MethodDelegate(string message); public static void Main(string[] args) { MethodDelegate mymethod = Console.WriteLine; mymethod("test"); Console.ReadLine(); }}