Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Why is the Main() method use in C# static?
The Main() method in C# is declared as static because it serves as the entry point of the program and must be callable without creating an instance of the class. When a C# program starts, no objects exist yet, so the runtime needs a way to begin execution without instantiation.
Why Main() Must Be Static
The static keyword allows the method to be called directly on the class rather than on an instance. Since the program hasn't created any objects when it starts, the Main() method must be accessible without instantiation −
Syntax
The standard syntax for the Main() method is −
static void Main(string[] args) {
// Program entry point
}
Alternative valid signatures include −
static void Main() { }
static int Main(string[] args) { }
static int Main() { }
Example with Static Main()
using System;
namespace Demo {
class HelloWorld {
static void Main(string[] args) {
Console.WriteLine("Program started - no object needed!");
// Now we can create objects
HelloWorld obj = new HelloWorld();
obj.DisplayMessage();
}
public void DisplayMessage() {
Console.WriteLine("Instance method called after object creation");
}
}
}
The output of the above code is −
Program started - no object needed! Instance method called after object creation
Understanding Main() Method Components
Breaking down the Main() method signature −
static void Main(string[] args)
-
static − Method belongs to the class itself, not to any instance
-
void − Method returns no value (can also return
intfor exit codes) -
Main − The specific method name that the runtime looks for as the entry point
-
string[] args − Array of command-line arguments passed to the program
What Happens Without Static
If Main() were not static, the runtime would need to create an instance of the class first, but this creates a circular dependency problem −
using System;
class Program {
// This would cause a compilation error
// void Main() { } // Error: Program does not contain a static 'Main' method
static void Main(string[] args) {
Console.WriteLine("Static Main() allows program to start");
Console.WriteLine("Without static, the runtime couldn't call this method");
}
}
The output of the above code is −
Static Main() allows program to start Without static, the runtime couldn't call this method
Conclusion
The Main() method is static because it serves as the program's entry point and must be callable without creating class instances. This design allows the .NET runtime to start program execution immediately when no objects exist yet, making it the foundation for all C# application startup.
