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
Valid variant of Main() in C#
The Main method is the entry point for all C# programs. It defines what the class does when executed. When you run a C# application, the runtime looks for the Main method and begins execution from there.
Syntax
There are several valid variants of the Main method in C# −
static void Main() static void Main(string[] args) static int Main() static int Main(string[] args)
Parameters
-
static − the object is not needed to access static members. The Main method must be static so the runtime can call it without creating an instance of the class.
-
void/int − return type of the method. Use
voidwhen no return value is needed, orintto return an exit code. -
Main − entry point for any C# program. Program execution begins here.
-
string[] args − optional parameter for command line arguments passed to the program.
Using Main with void Return Type
Example
using System;
namespace Program {
public class Demo {
public static void Main(string[] args) {
Console.WriteLine("Welcome!");
Console.WriteLine("Program completed successfully.");
}
}
}
The output of the above code is −
Welcome! Program completed successfully.
Using Main with int Return Type
Example
using System;
namespace Program {
public class Demo {
public static int Main(string[] args) {
Console.WriteLine("Application started");
try {
Console.WriteLine("Processing completed");
return 0; // Success
}
catch (Exception ex) {
Console.WriteLine("Error: " + ex.Message);
return 1; // Error
}
}
}
}
The output of the above code is −
Application started Processing completed
Using Command Line Arguments
Example
using System;
namespace Program {
public class Demo {
public static void Main(string[] args) {
Console.WriteLine("Number of arguments: " + args.Length);
if (args.Length > 0) {
Console.WriteLine("Arguments passed:");
for (int i = 0; i
The output of the above code is −
Number of arguments: 0
No arguments provided.
Valid Main Method Variants Comparison
| Variant | Use Case | Return Value |
|---|---|---|
| static void Main() | Simple programs without command line arguments | None |
| static void Main(string[] args) | Programs that need command line arguments | None |
| static int Main() | Programs that need to return exit codes | Integer exit code |
| static int Main(string[] args) | Programs with both command line arguments and exit codes | Integer exit code |
Conclusion
The Main method serves as the entry point for C# applications and must be static. You can choose from four valid variants depending on whether you need command line arguments and return values. The most commonly used variant is static void Main(string[] args).
