How to use base method's local function's in overriden method

485 views Asked by At

If I had this code:

public virtual void Foo()
{
    void Bar()
    {
        // do important stuff for Foo
    }
}

// In a child class: 
public override void Foo()
{
    Bar();        // Doesn't work
    base.Bar();   // Also doesn't work
}

Is there anyway to call the local function defined in Bar inside of Foo without making Bar a normal method?

2

There are 2 answers

1
Eric Lippert On BEST ANSWER

Is there anyway to call the local function defined in Bar inside of Foo without making Bar a normal method?

There is no by-design way. That's what "local" means. A local is accessible by name only by code in the location of the declaration; that's why they're called "locals".

Is there "any" way? Sure, you could do all kinds of shenanigans with reflection and decompilation and unsafe code and so on. Please don't. Those are implementation details of the compiler; don't try to reverse-engineer them and certainly do not rely on any implementation choice the compiler team has made being permanent!

6
John Wu On

Yes, you can pass around a delegate to it just as you do with any lambda expression. And no, this doesn't break any "rules," and we do it in Javascript all the time, under the module pattern, or whatever it's called.

public class MyBase
{
    protected Action Foo()
    {
        return Local;

        void Local()
        {
            Console.WriteLine("Hello world");
        }
    }
}

public class MyDerived : MyBase
{
    public void HelloWorld()
    {
        var f = Foo();
        f();
    }
}


public class Program
{
    public static void Main()
    {
        var o = new MyDerived();
        o.HelloWorld();
    }
}

Output:

Hello world

Link to DotNetFiddle