Introduction
Local functions are a new feature in C# 7 that allows defining a function inside another function.
Local functions are similar to anonymous methods. Sometimes it's not necessary to create a named function to perform a specific action because the functionality is only local to a specific function, and a named function would only pollute the outer scope
The main goal of Local Functions is encapsulation so the compiler is enforcing that such functions cannot be called from anywhere else in the class. Consider the below example:
- class SampleLocalFunction {
- {
- get {
- return $ @ "{GetFirstName()} {GetLastName()}";
- string GetFirstName() => "Prasad";
- string GetLastName() => "Raveendran";
- }
- }
- }
Here, we have a getter property, which is composing a FullName comprised of two different sections. Each section is being retrieved through separate private methods. We have encapsulated methods usage by Local Functions.
Common places where local functions are defined:
- Methods
- Constructors
- Property accessors
- Event accessor
- Lambda expressions
- Finalizers, a.k.a destructors
- Local functions (meaning local functions can be nested within each other)
Generic Local Function
Generic functions combine reusability, type safety, and efficiency. They are often used with collections and methods, which operate on them.
Example below:
- class Program {
- static void Main(string[] args) {
- void MyGeneric < Value > (Value x) {
- Console.WriteLine($ "Value from generic message: {x}");
- }
- MyGeneric < string > ("Next Year");
- MyGeneric < int > (2021);
- Console.ReadKey();
- }
- }

Join the conversation! Your thoughts help the community grow.