c# : console application - static methods
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 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.