Dec 8, 2019 in Dot Net
Q: Static local functions in C#

1 Answer

0 votes
Dec 8, 2019

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;


    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:


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

    static int Add(int left, int right) => left + right;
Click here to read more about Loan/Mortgage
Click here to read more about Insurance