.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?
CodePudding user response:
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