Search code examples
c#program-entry-pointstatic-classes

Why do Win Forms Apps have Main in a static class and should I stay within in


Windows Forms Application projects place the Main method inside of a static class.

This is strange and uncomfortable for me coming from Java, and being a fairly novice programmer to begin with. I have several quick questions to help me better understand what's going on and how this should be handled according to convention.

  • Why is this class static by default
  • Should I create a new instance of a non-static public class in Main and work from that class from then on
  • If not, how should I go about writing an application where the entry point is within a static class (structurally)

Solution

  • In order to start the program, you need an object and the instance of its method. In this case, for example, in order to start your Windows App, the main entry point of CLR usually on this case is this "Program.cs". So you need to call Program then call its static method. A simple code representation could be this:

    //Example Entry point of Program just for interpretation
    public static class Foo
    {
        private static int  intID { get; set; }
        public static string  strName { get; set; }
    
        public static string Start()
        {
            return "Program run successfully";
        }
    }
    

    If this is the entry point of CLR, in order to launch and call it, you just simply:

    Foo.Start();
    

    In WinForm case its:

    Program.Main();
    

    Keep in mind that Program.cs is just a default project template. You could delete that and write the Main function inside other class or even rename the static class with static Main on it.

    On your second question, that would be a Yes.