C# local functions are private methods of the same type as the one in which they are declared. These functions can only be invoked from within the member that contains them.
Local functions are employed to enhance code clarity and readability.
We can declare local function in the following scope.
- Methods
- Constructors
- Property accessors
- Event accessors
- Anonymous methods
- Lambda expressions
- Finalizers
- Other local functions
A local function is a function defined within another function, and it follows the syntax below.
C# Local Function Syntax
<modifiers: async | unsafe> <return-type> <method-name> <parameter-list>
Local functions do not permit the use of access modifiers, not even 'private'. Local variables' members are implicitly private.
Let's see an example.
C# Local Function Example
using System;
namespace CSharpFeatures
{
public class LocalMethodExample
{
public static void Main(string[] args)
{
int result = add(10, 20); // calling local method
Console.WriteLine("sum of 10 and 20 is: " + result);
// Creating local method
int add(int a, int b)
{
return a + b;
}
}
}
}
Output:
sum of 10 and 20 is: 30