What are local functions in c# 7.0?
In C# 7.0, local functions allow programmers to define a new function inside the body of a pre-existing function. The scope of the inner function is local to the outer function used to create it.
A local function can only be called inside its outer function.
Syntax
<return-type> <method-name> <parameter-list>
Semantics
The semantics of a local function is a little different than that of regular functions.
A local function does not support overloading, and the static keyword and attributes cannot be applied to its parameters or parameter type.
Similarly, member access modifiers, such as the keyword private, must not be used inside the body of a local function as members of a local function are private by default.
Advantages
The advantages of local functions are manyfold:
- Local functions make the code more readable and prevent function calls by mistake, as a local function may only be called inside its outer function.
- A local function supports the
asyncandunsafemodifiers. - C# 7.0 allows us to define multiple local functions in the body of one function.
- A local function is able to access the variables declared in the outer function, as well as its parameters.
Example
The following program declares a local function in the body of a pre-existing function, which prints the values of the variables declared in the outer function, as well as the variables passed to it as parameters.
Values of variables are printed using the Console.WriteLine function.
using System;public class Program {// Main functionpublic static void Main(){//variables declared inside the outer functionint a=5;int b=50;void print_variables(int c, int d){//printing variables declared inside the outer functionConsole.WriteLine("Value of a is: " + a);Console.WriteLine("Value of b is: " + b);//printing variables passed as parameters to the local functionConsole.WriteLine("Value of a is: " + c);Console.WriteLine("Value of b is: " + d);}// Inner or local function calledprint_variables(20, 40);}}
The output of this program is as follows:
Value of a is 5
Value of b is 50
Value of c is 20
Value of d is 40
Free Resources