why in C#, console application, in "program" class , which is default, all methods have to be static along with
static void Main(string[] args)
why in C#, console application, in "program" class , which is default, all methods have to be 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 an object at first - only the class template in memory and its static Main entry method.
A static method can only directly call other static methods on the same class (unless there is an instance handle of something to use), and that's why Main calls other static methods (and why you get a compile error if you have a non-static methods being called).
However if you create an instance of any class (even of the Program class itself) then you start creating instances in your application on the heap, and you can start calling instance methods and members on those things.
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.