Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a Local Function over an Action as an input param

Tags:

c#

c#-7.0

I have a method that is taking in an Action<string> (see simple example below), but in the calling method where the Action is constructed, Resharper is suggesting that a Local Function should be used.

What are the recommended practices around using Local Functions in place of Actions, does it matter, or are there gotchas to be aware of?

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");
}
like image 431
Ayb4btu Avatar asked Oct 12 '17 03:10

Ayb4btu


1 Answers

Taking you code and putting it through sharplab.io, we can see that the code gets lowered 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");
    }
}

Because both act and SetHolder are closures over holder, when Caller is invoked a new closure class instance is created and new Action delegates are created for both the lambda and the local function. So the resultant code is identical for both.

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

like image 119
David Arno Avatar answered Oct 15 '22 10:10

David Arno