Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Using C# 7's Local Function Feature for Multiple Sequential Exit Test Scenarios

4.83/5 (5 votes)
2 Apr 2019CPOL1 min read 17.1K  
Where a function requires execution in stages, and a check for an exit condition after/with each stage

Introduction

Mads Torgersen described the use of C# 7's Local Function feature as:

You want a helper function. You are only using it from within a single function, and it likely uses variables and type parameters that are in scope in that containing function. On the other hand, unlike a lambda you don't need it as a first class object, so you don't care to give it a delegate type and allocate an actual delegate object. Also you may want it to be recursive or generic, or to implement it as an iterator.

A recent article here by Florian Rappl, Modernize Your C# Code - Part II: Methods, shows one implementation of this flow-of-control pattern using the Local Function feature; this tip shows an implementation that, IMHO, is simpler, cleaner.

Rappl's code example:

C#
void LongFunction()
{
    void Cleanup()
    {
        // Define cleanup logic here
    }

    // ... many steps
    if (specialCondition)
    {
        // ...
        Cleanup();
        return;
    }

    // ... many steps
    if (specialCondition)
    {
        // ...
        Cleanup();
        return;
    }

    // ...many steps
    Cleanup();
}

An alternative:

C#
public void OuterFunction(int a, int b)
{
    void Innerfunction()
    {
        // ... many steps
        if (a > b)
        {
            // ...
            CleanUp();
        }

        // ... many steps
        if (a < b)
        {
            CleanUp();
        }
    }

    void CleanUp()
    {
        // Cleanup code
        return;
    }

    Innerfunction();
}

This code simplifies the tests, and the 'CleanUp function is never executed if not explicitly called; of course, you may want to have the 'CleanUp function always executed: that's a trivial change.

There is one aspect of this that may be a bit confusing to some: the use of 'return in the 'CleanUp function does appear to return to the inner function; and, on exit, one might assume that the inner function is going to get called again.

That does not happen: the 'return in the 'CleanUp function will exit the OuterFunction: single-step through it, and see for yourself.

Edit in response to 'Anker: in this example, the 'return statement in the 'CleanUp function exits the 'OuterFunction because there is no other executable code in the outer function. If you add code after the 'CleanUp function, it will be executed.

History

  • 2nd April, 2019: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)