C# 7 local functions in practice
Posted: (EET/GMT+2)
C# 7 introduced several new language features, and one of the most practical ones for everyday code is a feature called local functions. In short, a local function is a method defined inside another method. It helps keep small helper routines close to where they are used, without adding unnecessary methods at the class level scope.
Before C# 7, we often used lambdas or private methods for short operations, especially when validating parameters or performing small recursive tasks. With local functions, this now becomes cleaner and easier to read.
void ProcessFiles(string directory)
{
if (!Directory.Exists(directory))
{
throw new DirectoryNotFoundException(directory);
}
foreach (var file in Directory.GetFiles(directory))
{
Process(file);
}
void Process(string path)
{
Console.WriteLine($"Processing {Path.GetFileName(path)}");
// actual processing logic here
}
}
The "Process" function above is visible only inside the outer "ProcessFiles" method. It can access local variables and parameters from the enclosing scope without needing to pass them around explicitly. This makes the code compact while keeping related logic together.
Local functions are also very useful for small recursive algorithms. For example:
public int Fibonacci(int n)
{
if (n < 0) throw new ArgumentOutOfRangeException(nameof(n));
return Fib(n);
int Fib(int i)
{
if (i <= 1) return i;
return Fib(i - 1) + Fib(i - 2);
}
}
Because the recursive helper is local, there's no risk of it being called from outside or cluttering your class API. This is great for algorithms or validation helpers that make sense only within a single method.
Local functions can also be static if they don't need access to instance or outer variables. A nice optimization for small, self-contained helpers.
While not a revolutionary feature, local functions improve the readability and structure of everyday C# code. They help you express your intent clearly and keep related logic close together. This is something that has always been one of C#'s strengths, and one more reason to like the language.