Code inspection: Convert delegate variable into local function
Category: Language Usage Opportunities
ID: ConvertToLocalFunction
EditorConfig: resharper_convert_to_local_function_highlighting=[error|warning|suggestion|hint|none]
Language: C#
Requires SWA: No
tip
Local functions, unlike lambdas or delegates, do not cause additional overhead because they are essentially regular methods. For example, instantiating and invoking a delegate requires additional members being generated by the compiler and causing some memory overhead. Another benefit of local functions is their support for all the syntax elements allowed in regular methods. If it is possible to replace a delegate with local function, ReSharper suggests doing so.
Consider an example with a user-defined delegate. ReSharper replaces the delegate variable mymethod
with a local function Mymethod
. After the replacement, it also suggests removing the unused delegate MethodDelegate
.
Suboptimal code
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
class DelegateTest{ public static void Main(string[] args) { void Mymethod(string message) { Console.WriteLine(message); } Mymethod("test"); Console.ReadLine(); }}
In another example, ReSharper replaces a generic delegate Func
with a local function:
Suboptimal code
class ConvertToLambda{ public static int ConvertTest() { Func<int, int, int> sum = delegate(int x, int y) { return x + y; }; return sum(10, 20); }}
After the quick-fix
class ConvertToLambda{ public static int ConvertTest() { int Sum(int x, int y) { return x + y; } return Sum(10, 20); }}