Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What are Local functions in C# 7.0?
Local functions are private methods defined inside another member (method, constructor, or property). They are only accessible within their containing member and provide a clean way to break down complex logic into smaller, reusable pieces without exposing helper methods to the entire class.
Local functions were introduced in C# 7.0 and offer better performance than lambda expressions for recursive scenarios and provide compile-time checking for definite assignment.
Syntax
Following is the syntax for declaring a local function −
returnType LocalFunctionName(parameters) {
// function body
}
Local functions can be declared in and called from −
Methods, especially iterator methods and async methods
Constructors
Property accessors
Event accessors
Anonymous methods
Lambda expressions
Finalizers
Other local functions
Using Local Functions for Simple Operations
Example
using System;
class Program {
public static void Main() {
void addTwoNumbers(int a, int b) {
Console.WriteLine(a + b);
}
addTwoNumbers(1, 2);
}
}
The output of the above code is −
3
Using Local Functions with Out Parameters
Example
using System;
class Program {
public static void Main() {
void addTwoNumbers(int a, int b, out int c) {
c = a + b;
}
addTwoNumbers(1, 2, out int c);
Console.WriteLine(c);
}
}
The output of the above code is −
3
Local Functions Accessing Local Variables
Local functions can access variables from their containing method, creating closures −
Example
using System;
class Program {
public static void Main() {
int multiplier = 5;
int MultiplyByFive(int number) {
return number * multiplier;
}
Console.WriteLine("3 x 5 = " + MultiplyByFive(3));
Console.WriteLine("7 x 5 = " + MultiplyByFive(7));
}
}
The output of the above code is −
3 x 5 = 15 7 x 5 = 35
Local Functions vs Lambda Expressions
| Local Functions | Lambda Expressions |
|---|---|
| Declared with method syntax | Declared as delegates or expressions |
| Better performance for recursion | Slightly more overhead due to delegate creation |
| Can use ref and out parameters | Cannot use ref and out parameters |
| Compile-time name resolution | Runtime delegate creation |
Conclusion
Local functions in C# 7.0 provide a clean way to create helper methods that are only needed within a specific scope. They offer better performance than lambda expressions for recursive operations and can access local variables from their containing method, making code more organized and maintainable.
