c# : console application - static methods

前端 未结 5 593
[愿得一人]
[愿得一人] 2020-12-24 01:26

why in C#, console application, in \"program\" class , which is default, all methods have to be static along with

static void Main(string[] args)

相关标签:
5条回答
  • 2020-12-24 01:34

    The Main method is static because it's the code entry point to the assembly. There is no instance of any object at first, only the class template loaded in memory and its static members including the Main entry point static method. Main is predefined by the C# compiler to be the entry point.

    A static method can only call other static methods (unless there is an instance handle of something composited for use). This is why the Main method calls other static methods and why you get a compile error if you try to call a non-static (instance) method.

    However, if you create an instance of any class, even of the Program class itself, then you start creating objects in your application on the heap area of memory. You can then start calling their instance members.

    0 讨论(0)
  • 2020-12-24 01:35

    So, technically correct answers are above :)

    I should point out that generally you don't want to go in the direction of all static methods. Create an object, like windows form, a controller for it and go towards object-oriented code instead on procedural.

    0 讨论(0)
  • 2020-12-24 01:36

    You can write non static methods too, just you should use like this

    static void Main(string[] args)
    {
        Program p = new Program();
        p.NonStaticMethod();
    }
    

    The only requirement for C# application is that the executable assembly should have one static main method in any class in the assembly!

    0 讨论(0)
  • 2020-12-24 01:45

    Member functions don't have to be static; but if they are not static, that requires you to instantiate a Program object in order to call a member method.

    With static methods:

    public class Program
    {
        public static void Main()
        {
            System.Console.WriteLine(Program.Foo());
        }
    
        public static string Foo()
        {
            return "Foo";
        }
    }
    

    Without static methods (in other words, requiring you to instantiate Program):

    public class Program
    {
        public static void Main()
        {
            System.Console.WriteLine(new Program().Foo());
        }
    
        public string Foo() // notice this is NOT static anymore
        {
            return "Foo";
        }
    }
    

    Main must be static because otherwise you'd have to tell the compiler how to instantiate the Program class, which may or may not be a trivial task.

    0 讨论(0)
  • 2020-12-24 01:50

    Not all methods have to be static, you can add instance methods and also create an instance of your Program class.
    But for Main it has to be static beacause it's the entry point of your application and nobody is going to create an instance and call it.

    0 讨论(0)
提交回复
热议问题