Why do local functions have the "internal" access modifier?

Viewed 261

Why does the Roslyn compiler generate local functions with the internal access modifier (in IL, assembly) instead of private?

    private void M()
    {
        bool f = true;
        bool x1() => f;
        static bool x2() => true;
    }
    .method assembly hidebysig static
        bool '<M>g__x1|0_0' (
            valuetype C/'<>c__DisplayClass0_0'& ''
        ) cil managed { ... }

    .method assembly hidebysig static
        bool '<M>g__x2|0_1' () cil managed { ... }

sharplab.io

Docs say that it should be private: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/local-functions

Local functions are private methods of a type that are nested in another member.

Because all local functions are private, including an access modifier, such as the private keyword, generates compiler error CS0106

1 Answers

Looks like code reuse artifact. Roslyn probably uses same code to handle local functions and lambdas, but injects method definitions in different classes.

In case of lambda it injects lambda body to generated closure (DisplayClass) class and it should be internal to be referenced from calling function.

Related