Definition
Local functions mean you can create a function within another function, and it encapsulates completely within that function.
Features Of Local Functions In C# 7.0
Parameters and local variables from the enclosing scope are visible within the local function.
Why I should think about Local functions?
Let's think about when you need a helper function, which will be called once.
In the old days, before C# 7, you could think in 2 ways.
- Create a private method inside the class and call it in the function, but that will end up having many private methods that wouldn’t be reused.
- Using Func and Actions types with the anonymous methods, this solution has a limitation, like you can’t use generics, out, ref, and params.
Now, in C# 7 world, you can declare a function inside another one.
Let's take some examples.
Example 1. In the code mentioned above, we created a function GetMyName() inside the Main Function.
using System;
class Program
{
static void Main(string[] args)
{
// Method calling
GetMyName();
}
// Method Declaration
static void GetMyName()
{
Console.WriteLine("My Name Is Omar Maher");
}
}
Let's run it and see the result.

Also, you can make a calling for the local function after the declaration, as shown below.
using System;
class Program
{
static void Main(string[] args)
{
// Method Declaration
void GetMyName()
{
Console.WriteLine("My Name Is Omar Maher");
}
// Method calling
GetMyName();
}
}
It will give you the same result.

Example 2. Also, you can declare the parameter into the local function, but it will be available in the scope of GetMyName(string name), as shown.
using System;
class Program
{
static void Main(string[] args)
{
// Method calling
GetMyName("Omar Maher");
}
// Method Declaration
static void GetMyName(string name)
{
Console.WriteLine($"My Name Is {name}");
}
}
When you run, you will get the same result.

Marlon González GóngoraPosted Jun 4, 2017, 9:11 PM
Thanks for sharing
Eman AhmedPosted May 21, 2017, 3:11 AM
Nice one :)..........
Jorge UribePosted May 10, 2017, 11:32 AM
I did a test as overload, but is not supported, is that correct ?
Tim TylerPosted May 10, 2017, 5:33 AM
Nice and clear, thanks. I think you repeat a typo throughout regarding the MyData 'Constructor' though.
abdullah ZayedPosted May 4, 2017, 4:08 AM
Nice ...............................................................
Rajesh KadamPosted May 2, 2017, 7:38 AM
Why do we need to create the local function if it is not going to need again..? I dont see any advantage of it.
Waruna ManjulaPosted May 2, 2017, 1:00 AM
Good.........................
Manav PandyaPosted May 2, 2017, 12:08 AM
Nice share ......................