C# 8.0 Static local function

C# 8.0 – Static local functions


Facebooktwitterlinkedinmail

C# 7.0 introduced local functions and with C# 8.0 one can create static local functions. Let’s have a look at what differentiates them.

Note: You can view all code examples on GitHub. My environment: Visual Studio 2019 16.4.6 and .NET Core App 3.1.

A local function allows embedding a method inside a method. So what’s new with static local functions? By default, every local function has access to variables in the containing scope (parent method). This is possible thanks to the compilator that generates a closure that contains all the variables. It’s very handy for a developer, but there is a dark side as well. Such an approach requires a memory allocation. Usually, it’s not a big deal, but in some scenarios, one would like to prevent the allocation.

Static local functions come with help. They don’t allow access to the variables. Meaning – no allocation. To change a local function to static local function one needs to add the static keyword.

void ParentMethod(int luckyNumber)
{
    var myNumber = luckyNumber + 2;

    LocalFunction();
    StaticLocalFunction();

    void LocalFunction()
    {
        Console.WriteLine("Local function has access to");
        Console.WriteLine($"* Parent parameter: {luckyNumber}");
        Console.WriteLine($"* Parent variable: {myNumber}");
    }

    static void StaticLocalFunction()
    {
        Console.WriteLine("Static local function - no access");

        // The below line would cause an error
        // myNumber++;
        // Error CS8421: A static local function cannot contain a reference to 'myNumber'.
    }
}

Of course, it’s still possible to pass variables to a static local function – just by passing it as a method parameter.

void ParentMethod(int luckyNumber)
{
    StaticLocalFunction(luckyNumber);

    static void StaticLocalFunction(int value)
    {
        Console.WriteLine($"Static local function with parameter: {value}");
    }
}

To sum up, static local functions are local functions without access to the parent’s scope and smaller memory footprint.

Facebooktwitterlinkedinmail

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.