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. void means no return value, int returns 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.

Main() Method Components static void Main ( string[] args ) Access Modifier Return Type Method Name Command Line Arguments

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 be static so it can be called without creating an instance.

  • It can return void or int. When returning int, the value represents the exit code.

  • The string[] args parameter 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.

Updated on: 2026-03-17T07:04:35+05:30

847 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements