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

By | August 2, 2017

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.

 

2 thoughts on “Helper function for your local method – Local Function in C# 7.0

  1. Pingback: Dew Drop - August 3, 2017 (#2534) - Morning Dew

  2. Pingback: Expression Bodied Local Function in C# 7.0

Leave a Reply

Your email address will not be published. Required fields are marked *