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:
void LongFunction()
{
void Cleanup()
{
}
if (specialCondition)
{
Cleanup();
return;
}
if (specialCondition)
{
Cleanup();
return;
}
Cleanup();
}
An alternative:
public void OuterFunction(int a, int b)
{
void Innerfunction()
{
if (a > b)
{
CleanUp();
}
if (a < b)
{
CleanUp();
}
}
void CleanUp()
{
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