Search code examples
c#extension-methodslocal-functions

Local extension method


Sometimes it becomes necessary to write some helper that is applicable only in the code of some method. I've tried to write extension method locally (as in static local functions), but the program does not compile.

The minimal repeatable example:

public static class Program {
    public static void Main() {
        static string ToLowerFirst(this string str)=>!string.IsNullOrEmpty(str) && char.IsUpper(str[0])?str.Length == 1 ? char.ToLower(str[0]).ToString() : char.ToLower(str[0]) + str[1..]:str;
      
        string s = "CamelCase";
        Console.WriteLine(s.ToLowerFirst());
    }
}

Error text: [CS1106] Extension methods must be defined in a non generic static class. Extension methods must be defined as static methods in a non-generic static class.

I did something wrong?

What the actual class of method with full name Program.<Main>g__ToLowerFirst|0_0?


Solution

  • It's quite simple, extension methods can't be local.

    The help message could be a little more helpful, because your method is defined in a non-generic static class, but crucially it's also inside of another method and that's your dealbreaker.

    I suspect that's because the error message has existed a lot longer than local functions have.


    If you move your method outside of main(), you should be okay but it won't be local anymore.