I am here to start a series related C# 7.0 features. Today, we will be going through one of the features called Local Functions and will demonstrate the uses in an easy way.
Local Function
Local function is a kind of inner function, sub-function or function within a function that can be declared and defined within parent method. We have the inner class concept from quite some time. Noe, it has been propagated to function as well.
Any piece of code that is required only on any particular method can be put as an inner function. The few examples could be,
- Small helper function to be used several times in a main or parent method.
- Parameter validation function for any iterators or asynchronous method.
- An alternate to recursive functions as local function comparatively takes less memory due to reduced call stack.
The below diagram depicts the scope of variety of functions.
Features of Local function
- Local function can be declared and defined inside any method, constructor, and properties.
- In the runtime, compiler translates Local function as static method; hence they can’t be declared as static explicitly.
- Local function supports generics, ref/out etc.
Is Local function concept really new?
Not really, it was kind of possible with Func and Action delegate even in older versions of C# but with some constraints. For example,
- Func and Action can’t use the generics
- Func and Action can’t use ref and out parameters
- Func and Action can’t use params and optional parameters.
- Calling Func and Action has more memory overhead than Local functions.
Working with Local Function
Enough theory! Now, let’s look at how to work with them.
The below code snippet shows two examples, one with regular way (i.e. GetFullAddress) and another using local function (GetFullAddressUsingLocalFunc).
- class Program
- {
- static void Main(string[] args)
- {
- Console.WriteLine("Full Address: " + LocalFunc.GetFullAddress());
- Console.WriteLine("Full Address using Local Function: " + LocalFunc. GetFullAddressUsingLocalFunc());
- }
- class LocalFunc
- {
- public static string GetFullAddress()
- {
- return "Gram/Post-Beeda, Via-Amarpatan, District - Satna, MP";
- }
- public static string GetFullAddressUsingLocalFunc()
- {
- var fullAddr = GetBasicAddress() + ", District - Satna, MP";
- return fullAddr;
- string GetBasicAddress()
- {
- return "Gram/Post-Beeda, Via-Amarpatan";
- }
- }
- }


Lalit RaghavPosted Aug 31, 2019, 4:33 AM
Nice article
Ashish VishwakarmaPosted Apr 29, 2017, 10:32 AM
Isn't this just a fancy wrapper around Func delegate?
Manav PandyaPosted Mar 21, 2017, 12:19 AM
Thanks for sharing sir .....