0 votes
in Dot Net by
Static local functions in C#

1 Answer

0 votes
by

You can now add the static modifier to local functions to ensure that local function doesn't capture (reference) any variables from the enclosing scope. Doing so generates CS8421, "A static local function can't contain a reference to <variable>."

Consider the following code. The local function LocalFunction accesses the variable y, declared in the enclosing scope (the method M). Therefore, LocalFunction can't be declared with the static modifier:

int M()

{

    int y;

    LocalFunction();

    return y;

    void LocalFunction() => y = 0;

}

The following code contains a static local function. It can be static because it doesn't access any variables in the enclosing scope:

C#Copy

int M()
{
    int y = 5;
    int x = 7;
    return Add(x, y);

    static int Add(int left, int right) => left + right;
}

Related questions

+1 vote
asked Jun 25, 2019 in Dot Net by Venkatshastri
0 votes
asked Dec 8, 2019 in Dot Net by Sinaya
...