C# local functions are the private methods having same type in which it is defined. Local function can be called only from its container member.
Local functions are used to make code clear and readable.
We can declare local function in the following scope.
- Methods
- Constructors
- Property accessors
- Event accessors
- Anonymous methods
- Lambda expressions
- Finalizers
- Other local functions
Local function is a nested function and has the following syntax.
C# Local Function Syntax
Example
<modifiers: async | unsafe> <return-type> <method-name> <parameter-list>
Local methods do not allow access modifiers even private. Members of local variable are private implicitly.
Let's see an example.
C# Local Function Example
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:
Output
sum of 10 and 20 is: 30