DEV Community

Juarez Júnior for Develop4Us

Posted on • Edited on

C# Tip: Static Local Functions

Let’s talk about Static Local Functions, introduced in C# 8, which allow you to declare local functions inside methods that do not capture instance variables. See the example in the code below.

public class Program
{
    public static void Main()
    {
        int result = Add(5, 10);
        Console.WriteLine($"Result of addition: {result}");

        static int Add(int a, int b)
        {
            return a + b; // Does not capture external variables because it is static
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Explanation:
With Static Local Functions, you can declare functions inside a method that do not depend on external variables or fields. By marking a local function as static, the compiler ensures that the function cannot access any external context, such as instance or method variables, which can help with optimization and code safety. In the example above, we use a static local function to perform an operation that does not depend on the class state.

Source code: GitHub

I hope this tip helps you use Static Local Functions to improve performance and safety in your code! Until next time.

Top comments (0)