in Dot Net by
Q:
Static local functions in C#

▼ Show 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;
}
Learn More with Madanswer

Related questions

...