Search code examples
c#recursionlocal-functions

How to call a function recursively if it contains a local function with the same name?


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
    }
}

Solution

  • 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.