Using a local function on an action as an input parameter

I have a method that takes in an Action<string> (see a simple example below), but in the calling method where the Action built, Resharper suggests using a Local function.

What are the recommended methods for using local functions instead of actions, does it matter or are there any issues you need to know about?

 public void Caller() { string holder; Action<string> act = s => holder = s; void SetHolder(string s) => holder = s; DoStuff(act); DoStuff(SetHolder); } public void DoStuff(Action<string> setHolder) { setHolder("holders new string"); } 
+5
source share
2 answers

Taking the code and putting it through sharplab.io , we can see that the code drops to:

 public class Class { [CompilerGenerated] private sealed class <>c__DisplayClass0_0 { public string holder; internal void <Caller>b__0(string s) { this.holder = s; } internal void <Caller>g__SetHolder1(string s) { this.holder = s; } } public void Caller() { Class.<>c__DisplayClass0_0 @object = new Class.<>c__DisplayClass0_0(); Action<string> setHolder = new Action<string>(@object.<Caller>b__0); this.DoStuff(setHolder); this.DoStuff(new Action<string>(@object.<Caller>g__SetHolder1)); } public void DoStuff(Action<string> setHolder) { setHolder("holders new string"); } } 

Since both act and SetHolder are closures over holder , when Caller is called, a new instance of the closure class is created, and new Action delegates are created for the lambda and local function. Thus, the resulting code is identical for both.

Therefore, given how you use them here, it just comes down to readability (as many R # recommendations do). Local functions may have better syntax, so R # recommends using it that way.

+6
source

One of the advantages of local functions over delegates is that their invocation is not related to instantiating the delegate and invoking the delegate that is lost in your example because you end it with a delegate to pass it to DoStuff .

Take a look to know all about local functions .

-1
source

Source: https://habr.com/ru/post/1272543/


All Articles