Helper function for your local method – Local Function in C# 7.0

Helper function for your local method – Local Function in C# 7.0

In C# 7.0, you can now have your helper function defined with in the method itself. The local function can access all the local variables, and can also make use of lambda expression or even async-await. However, They aren’t available outside though.

 

Local Function.PNG
Illustration of Local Function

 

As shown the below snippet, we have defined a local function named MyLocalFunction(), which accepts two parameter and same method used within the method.

class Program
{
static void Main(string[] args)
{
int val = 100;
int MyLocalFunction(int value1, int value2)
{
return val + value1 + value2;
}

Console.WriteLine(MyLocalFunction(10, 10));
}
}

Can we have more than one local function ?

Of course, you can have multiple local functions with in a method and you can call them internally as like another method.

 

MultipleLocalFunction.PNG
Illustration of Multiple Local Function

 

Refer to the below snippet.

class Program
{
static void Main(string[] args)
{
int val = 100;
int MyLocalFunction(int value1, int value2)
{
return val + value1 + value2;
}

int AnotherLocalFunction(int value1)
{
return MyLocalFunction(10, 12) + value1;
}

Console.WriteLine(MyLocalFunction(10, 10));
Console.WriteLine(AnotherLocalFunction(110));
}
}

Here is how the execution looks like using Code Maps

Local Function Inner.PNG

Can we have Nested Local function ?

Yes, Local function can also contain another local function – refer the  below snippet.

static void Main(string[] args)
{
int val = 100;
int MyLocalFunction(int value1, int value2)
{
return val + value1 + value2;
}

int AnotherLocalFunction(int value1)
{
int GetRandomValues()
{
return new Random().Next(100);
}

return MyLocalFunction(GetRandomValues(), GetRandomValues()) + value1;
}

Console.WriteLine(MyLocalFunction(10, 10));
Console.WriteLine(AnotherLocalFunction(110));
}

You have to keep in mind, Local Function – are just like a function and even though they are in between your method execution cycle, they won’t invoke unless you call them explicitly.

As said earlier, you can make use of Async-Await, Out/ref and generics with your local function. With all that, local function became very powerful that help organizes your code and help optimize the repeating code within a method.

 

Abhijit Jana

Abhijit runs the Daily .NET Tips. He started this site with a vision to have a single knowledge base of .NET tips and tricks and share post that can quickly help any developers . He is a Former Microsoft ASP.NET MVP, CodeProject MVP, Mentor, Speaker, Author, Technology Evangelist and presently working as a .NET Consultant. He blogs at http://abhijitjana.net , you can follow him @AbhijitJana . He is the author of book Kinect for Windows SDK Programming Guide.

2 Comments to “Helper function for your local method – Local Function in C# 7.0”

Comments are closed.