开发者

c# : console application - static methods

why in C#, console application, in "program" class , which is default, all methods have to be 开发者_JAVA技巧static along with

static void Main(string[] args)


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.


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!


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.


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜