0
0
C Sharp (C#)programming~5 mins

Main method as entry point in C Sharp (C#)

Choose your learning style9 modes available
Introduction

The Main method is where a C# program starts running. It tells the computer what to do first.

When you want to create a program that runs from the command line.
When you need a starting point for your application.
When you want to control the flow of your program from the beginning.
When you want to accept input arguments when the program starts.
When you want to return a status code after the program finishes.
Syntax
C Sharp (C#)
static void Main(string[] args)
{
    // code to run
}

static means you can run Main without creating an object first.

void means Main does not return any value.

Examples
Main method without parameters, just runs code inside.
C Sharp (C#)
static void Main()
{
    Console.WriteLine("Hello World");
}
Main method with string array to accept command line arguments.
C Sharp (C#)
static void Main(string[] args)
{
    Console.WriteLine($"You passed {args.Length} arguments.");
}
Main method returning an integer status code to the operating system.
C Sharp (C#)
static int Main(string[] args)
{
    Console.WriteLine("Program finished.");
    return 0;
}
Sample Program

This program starts in Main. It checks if any arguments were passed and prints a message accordingly.

C Sharp (C#)
using System;

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Program started.");
        if (args.Length > 0)
        {
            Console.WriteLine($"First argument: {args[0]}");
        }
        else
        {
            Console.WriteLine("No arguments passed.");
        }
        Console.WriteLine("Program ended.");
    }
}
OutputSuccess
Important Notes

The Main method must be inside a class or struct.

You can have Main return void or int depending on if you want to send a status code.

Arguments passed to Main come from the command line when you run the program.

Summary

The Main method is the starting point of a C# program.

It can accept arguments and optionally return a status code.

It must be static and inside a class or struct.