'.NET 6: How to use method overloading in console app Startup?

.NET 6 offers boilerplate-removal in console applications Startup class. I try to run this simple test code:

Console.WriteLine("Hello, World!");

static void Test(int a, int b) { }

static void Test(int a, int b, int c) { }

I'm getting compiler error in the last line:

Error   CS0128  A local variable or function named 'Test' is already defined in this scope

My question is: How to use method overloading in boilerplate free Startup pattern?



Solution 1:[1]

This

Console.WriteLine("Hello, World!");

static void Test(int a, int b) { }

is compiled to

[CompilerGenerated]
internal class Program
{
    private static void <Main>$(string[] args)
    {
        Console.WriteLine("Hello, World!");
        static void Test(int a, int b)
        {
        }
    }
}

You see that the method is a local method, ie declaring inside Main. You cannot have 2 local functions with the same name. THis also fails;

see https://github.com/dotnet/docs/issues/17275

namespace Foo {
    class Program {

      //  SerialPort port;  
        static void Main(string[] args) {
            static void Test(int a) { };
            static void Test(int a, int b) { };

    }
}

for the same reason. The new short Main syntax has an awful lot of limitations

Solution 2:[2]

You can still create a class and put all the methods you want to overload. That's what I did. It works fine even if you can add access modifiers because as @pm100 said, the methods after compilation are in the main method

[CompilerGenerated]
internal class Program
{
  private static void <Main>$(string[] args)
   {
       Console.WriteLine("Hello, World!");
       static void Test(int a, int b)
       {
       }
   }
}

so it's the same for access modifiers but hopefully the next version of .NET won't have this problem anymore but for now you can always use a previous version that keeps the "Main" method.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Error404