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.
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.
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
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.
Pingback: Dew Drop - August 3, 2017 (#2534) - Morning Dew
Pingback: Expression Bodied Local Function in C# 7.0