C# 7.0 – Local Functions

In this article, we will discuss one of the planned language features in C# 7.0

Local functions are functions that you define inside another function. C#7.0 will allow you to declare functions in the body of other functions.

Like Lambda expressions, Parameters and local variables from the enclosing scope are available inside of a local function.


Methods implemented as iterators need a non-iterator wrapper method for checking the arguments at the time of the call. More On CSharp

If Iterator had been a private method next to Employee, it would have been available for other members to accidentally use directly (without argument checking). Also, it would have needed to take all the same arguments as Employee instead of having them just be in scope.

Advantage of using Local Functions:

– Like lambdas, local functions can capture local variables and parameters of their containing method
– Local functions support recursion like any normal methods
– They don’t require you to allocate a delegate to hold them. This reduces memory pressure and also allows the function to be in-lined by the compiler.
– They don’t require you to allocate an object when creating a closure because it has access to the local variables. Also, this improves performance by reducing GC pressure.
You can read more planned C#7.0 features here.

You can try this feature yourself using Visual Studio 15 Preview 4.

Please Note, In visual studio 15 Preview 4, local functions must be declared before they are called. This restriction will be loosened, so that they can be called as soon as local variables they read from are definitely assigned.

Thanks for Visiting!!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s