Edit

Share via


Compiler Error CS8422

A static local function cannot contain a reference to 'this' or 'base'.

The static keyword on a local function prevents the local function from accessing the state of parent instance methods or instances fields.
This error indicates the local function accesses instance members of the containing type.

Example

The following sample generates CS8422:

public class C
{
    private int counter = 1;
    public void IncreaseCounter()
    {
        static void localFunc(int addition)
        {
            this.counter += addition;   // CS8422 due to reference to 'this'
            base.ToString();            // CS8422 due to reference to 'base'

            // Also for implicit 'this' or 'base' references:
            counter += addition;   // CS8422 due to implicit reference to 'this'
            ToString();            // CS8422 due to implicit reference to 'base'
        }
        localFunc(10);
        Console.WriteLine(this.counter);
    }
}

To correct this error

If there is an intention of local function to capture and modify the state of a parent then it shouldn't be declared static. You could also remove access to any instance members.

public class C
{
    private int counter = 1;
    public void IncreaseCounter()
    {
        void localFunc(int addition)
        {
            counter += addition;
            ToString();
        }
        localFunc(10);
        Console.WriteLine(this.counter);
    }
}

public class Program
{
    public void Main()
    {
        C c = new();
        c.IncreaseCounter();
    }
}

// Output:
// 11

See also