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
How to use the Main() method in C#?
The Main() method in C# is the entry point of any C# application. It is a static method that runs when the program starts, without requiring an instance of the class to be created. The Main() method defines what the class does when executed and can instantiate other objects and variables.
Syntax
Following are the valid signatures for the Main() method −
static void Main() static void Main(string[] args) static int Main() static int Main(string[] args)
Parameters
The Main() method signature includes the following components −
-
static − The method belongs to the class itself, not to any instance. No object creation is needed to access it.
-
void/int − The return type.
voidmeans no return value,intreturns an exit code to the operating system. -
Main − The method name. This is the entry point where program execution begins.
-
string[] args − Optional parameter for command-line arguments passed to the program.
Using Main() Method
Basic Example
using System;
namespace Demo {
class HelloWorld {
static void Main(string[] args) {
Console.WriteLine("Hello World!");
}
}
}
The output of the above code is −
Hello World!
Using Main() with Return Value
Example
using System;
namespace Demo {
class Program {
static int Main(string[] args) {
Console.WriteLine("Program executed successfully");
return 0; // 0 indicates successful execution
}
}
}
The output of the above code is −
Program executed successfully
Using Command-Line Arguments
Example
using System;
namespace Demo {
class Program {
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 < args.Length; i++) {
Console.WriteLine($"Arg[{i}]: {args[i]}");
}
} else {
Console.WriteLine("No arguments passed");
}
}
}
}
The output of the above code is −
Number of arguments: 0 No arguments passed
Key Rules
-
Every C# application must have exactly one Main() method as the entry point.
-
The
Main()method must bestaticso it can be called without creating an instance. -
It can return
voidorint. When returningint, the value represents the exit code. -
The
string[] argsparameter is optional and contains command-line arguments.
Conclusion
The Main() method is the entry point of every C# application and must be static. It can optionally accept command-line arguments and return an integer exit code to indicate the program's execution status.
