A great feature of C# 7.0 are local functions. Local functions have the syntax of methods and can be used within the scope of methods, properties, constructors…
With articles showing this feature, I often see questions: “What is it good for?” “Why is this needed?” To understand the usefulness of local functions, some good examples are needed. I try to show these with this article.
Local Functions with the yield Statement
Let’s start with a simplified filter method
Where. This implementation checks for
parameters resulting in an
ArgumentNullException in case null is passed:
Invoking this method, the ArgumentNullException is not thrown when the query statement is defined, but – because of the delayed execution of
yield, with the
foreach iteration in line 4:
For having error information when it is needed, the
Where method can be splitted into two methods. The Where method just checks the parameters without any
yield statement included in the implementation, and invokes the
WhereImpl method where the
yield is done.
With this in place, the ArgumentNullException happens in line 2 where the error is more helpful.
Where method has nothing than a parameter check and an invocation of the real implementation. Here, local functions are of great help. The implementation is simpler compared to the private method – the local function
Iterator can access variables from the outer scope, and thus here parameters are not needed:
Another scenario for local functions are recursive calls.
In the following implementation of the
Sort is a local function that is called recursively until the collection is sorted.
Using recursive calls with C# you need to be careful:
With C# you need to be careful with recursive calls. Contrary to functional programming languages like F#, the C# compiler does not tail call optimization where recursive method calls are converted to iterations to not consume call stack. With C# you can easily result in a
When does it end with the default stack configuration doing recursive calls with C#?
This simple sample that doesn’t need a lot of stack memory with every iteration ends after 24020 iterations with a
StackOverflowException, so be careful doing recursive calls with C#.
Local Functions instead of Lambda Expressions
Recently I came across an older sample where a Lambda expression is used in the
This one can be replaced by a local function as well:
This is just a matter of taste, but doesn’t look the syntax with the local function easier?
What are your thoughts on local functions with C# 7?
Have fun programming and learning,
Some more C# 7 articles: