I started a project with the new console template that uses top level statements, but I wanted to add Program Main
back in anyway.
However, when I add in the class like this:
// See https://aka.ms/new-console-template for more information
Console.WriteLine("Hello, World!");
public class Program
{
public static void Main()
{
Console.WriteLine("Hello World");
}
}
I get the error:
error CS0260: Missing partial modifier on declaration of type 'Program';
Another partial declaration of this type exists
Other stack overflow questions say to just add partial
, but when I do that, I get the error:
warning CS7022: The entry point of the program is global code;
ignoring 'Program.Main()' entry point
What's going on here?
The problem was I forgot to remove the
Console.WriteLine
at the top as well.Top level statements (added in C#9) will "compile down" into their own compiler generated
Program
class.You can use sharplab to inspect the following code:
Which will be compiled into something that looks like this:
So you have to get rid of your top level statements if you want to use
Program.Main
(and vice versa).There can only be one entry point