C #: console application - static methods

why in C #, the console application, in the "program" class, which by default, all methods must be static together with

static void Main(string[] args) 
+43
c # static
Nov 06 '09 at 5:58
source share
5 answers

Member functions do not have to be static; but if they are not static, this requires creating an instance of the Program object to call the 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, you need to instantiate a 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 should be static, because otherwise you would need to tell the compiler how to create an instance of the Program class, which may or may not be a trivial task.

+63
Nov 06 '09 at 6:00
source share

You can also write non-static methods, you just have to use this as

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

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

+22
Nov 06 '09 at 6:01
source share

The main method is static, because it indicates the input of code into the assembly. Initially, there is no instance of any object, only a template template loaded into memory and its static elements, including the static method of the main entry point. Main is the predefined C # compiler for the entry point.

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

However, if you create an instance of any class, even the class of the program itself, then you begin to create objects in your application in the heap area of ​​memory. Then you can call their instances.

+11
Nov 06 '09 at 6:01
source share

Not all methods must be static; you can add instance methods, as well as create an instance of your program class.
But for Main, it must be static, since it is the entry point of your application, and no one is going to instantiate and call it.

+5
Nov 06 '09 at 6:02
source share

So technically correct answers above :)

I should point out that usually you do not want to go in the direction of all static methods. Create an object, for example, a window shape, a controller for it, and go to the object-oriented code instead of the procedural one.

+1
Nov 06 '09 at 6:20
source share



All Articles