Why should the Main() method be static?

后端 未结 5 560
無奈伤痛
無奈伤痛 2020-12-08 04:34

I tried to create public void Main() in C#; it says no static void Main found.
What exactly does it mean for Main to be static? I kno

5条回答
  •  一生所求
    2020-12-08 04:58

    There are two types of method within a class:

    1. Non-static method
    2. Static method

    // Example of static and non-static methods and how to call
    namespace TestStaticVoidMain
    {
        class Program
        {
            Static Void Main(string[] args)
            {
               // Instantiate or create object of the non-static method:
                Exam ob = new Exam();
                // Call the instance:
                ob.Test1();
    
                // Directly the call the static method by its class:
                Exam.Test2();
    
                Console.ReadKey();
            }
        }
        class Exam
        {
            public void Test1()
            {
                Console.WriteLine("This is a non-static method");
            }
    
            public static void Test2()
            {
                Console.WriteLine("This is a static method");
            }
        }
    }
    

    1. Static method:

    To call a static method (function), we don't need to instantiate or create an object of that method. We can't use new keyword because, when the class is loaded and compiled, the static keyword by default instantiates or creates an object of that class method, so that is why we directly call a static method.

    In reference to static void Main(string[] args), we already discussed static. The remainder is void Main(string[] args). void is a data type which returns nothing. Main() is the standard entry point to execution of a C# program. The optional argument string[] args receives the optional "command line" parameters that the program was run with.

    2. Non-static sethod:

    To call a non-static method, we have to instantiate or create an object of the class method to call the method (function) of the class using the keyword new.

    If a class named Test has a non-static method named show(), then how it would call an instance:

    // to call non-static method
    Test ob=new Test();
    ob.show();
    

提交回复
热议问题