Why should the Main() method be static?
There are two types of method within a class:
- Non-static method
- 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();
No comments:
Post a Comment