In C#, the Main method is the entry point of every executable application. It marks where program execution begins and is typically defined as static void Main() or static void Main(string[] args).
Different Declarations of Main() Method
Below are the valid declarations of Main Method in a C# program:
1. With command line arguments
Command-line arguments in C# allow users to pass data to a program at startup. They are received through the string[] args parameter in the Main method.
Example:
using System;
class GFG {
// Main Method
public static void Main(String[] args){
Console.WriteLine("Main Method");
}
}
Output
Main Method
2. Without Command line arguments
In C#, the Main method can be written without parameters too and is defined as static void Main(). It simply starts program execution without accepting any external input.
Example:
using System;
class GFG {
// Main Method
public static void Main(){
Console.WriteLine("Main Method");
}
}
Output
Main Method
3. Applicable Access Modifiers
Main method can have the access modifiers public or private. Both are valid since the runtime can invoke Main regardless of its access level. However, public is commonly used for clarity, while private is equally acceptable.
Example 1: using public
using System;
class GFG {
// Main Method
protected static void Main(){
Console.WriteLine("Main Method");
}
}
Output
Main Method
Example 2: using private
using System;
class GFG {
// Main Method
private static void Main(){
Console.WriteLine("Main Method");
}
}
Output
Main Method
4. Without any access modifier
The default access modifier is private for a Main() method. If we don't provide any access modifier, compiler will take private access modifier by default.
Example:
using System;
class GFG {
// Main Method without any access modifier
static void Main()
{
Console.WriteLine("Main Method");
}
}
Output
Main Method
5. Order of Modifiers
The user can also swap positions of static and applicable modifiers in Main() method.
Example: Without swapping
using System;
class GFG {
// Main Method
public static void Main()
{
Console.WriteLine("Main Method");
}
}
Output
Main Method
Example: With swapping
using System;
class GFG {
// Main Method with swapping of modifiers
static internal void Main()
{
Console.WriteLine("Main Method");
}
}
Output
Main Method
6. Return Type
The Main Method can also have integer return type. Returning an integer value from Main() method cause the program to obtain a status information. The value which is returned from Main() method is treated as the exit code for the process.
Example:
using System;
class GFG {
// Main Method with int return type
static int Main()
{
Console.WriteLine("Main Method");
// for successful execution of code
return 0;
}
}
Output
Main Method
Example:
using System;
class GFG {
// Main Method with int return type
static int Main(String[] args)
{
Console.WriteLine("Main Method");
// for successful execution of code
return 0;
}
}
Output
Main Method