2

I was playing around the local functions and could not figure out how to call the host function if it contains the local function with the same name.

class Program
{
    static void Main(string[] args)
    {
        new Test().Foo();

        Console.Read();
    }
}

class Test
{
    public void Foo()
    {
        Console.WriteLine("Host function");

        void Foo()
        {
            Console.WriteLine("Local function");
        }

        Foo();  // This calls the local function

        Foo();  // I would like to call the host Foo() recursively here
    }
}
  • I trust this is just a general curiosity, the obvious solution of course is don't give the local function the same name as the outer function. – Rotem Jun 24 '18 at 12:09
  • @Rotem: Curiosity. Or not controling the name of the Functions. | Op: The only real requirement is that the compiler Unambigiously knows wich of those two functions with similar name is meant at any one time. Ideally you should invest work so the ambiguity does not exist to begin with. When in doubt a common approach is to wrap one class into a custom class you do control. Wrapping allows you to redifined anything about a classes function - name, signature. You can even turn Fields in Properties. The MVVM pattern uses encapsualtion a lot. – Christopher Jun 24 '18 at 12:15

1 Answers1

8

You could just prepend the call with this:

Foo(); // calls the local function
this.Foo(); // calls the class instance function

Though, even with a working workaround like this, it's still highly recommended to use better function names to more clearly distinguish between the two. Code can't be ambiguous to the compiler, but it really shouldn't be ambiguous to the person reading it either.

David
  • 208,112
  • 36
  • 198
  • 279