Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 182 ยท Getting Started

Program Structure: Top-Level Statements and Main

Learn how a C# program starts - top-level statements, the generated Program class, an explicit Main method, args, exit codes, async Main and file layout.

Every program needs an entry point: the place where the runtime starts executing. In C# that place is a method, traditionally named Main. For two decades you had to write it by hand inside a class. Since C# 9 you can simply write statements at the top of a file and let the compiler produce the entry point. Both styles are fully supported and compile to the same thing, so you will meet both: modern tutorials and new templates use top-level statements, while older code, libraries, and programs that need special control still use Main.

This lesson explains both forms, what the compiler generates behind the scenes, how to read command-line arguments, how to signal success or failure with an exit code, how to start asynchronous work, where types go relative to statements, and how a real project splits into several files.

Top-level statements

A file with top-level statements contains executable statements directly, with no class and no method around them.

C# A program with only top-level statements

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The statements run top to bottom, and the program ends after the last one. You can declare variables, call methods, use loops: everything you would put in Main. You can even use return with a value, as we do below.

What the compiler generates

The compiler takes your top-level statements and puts them in a method inside a hidden class. Conceptually this is what it builds:

C#
internal class Program
{
    private static void <Main>$(string[] args)
    {
        // your top-level statements go here
    }
}

The names Program and <Main>$ are invalid for you to type, so they cannot clash with your own code. You can prove the entry point exists by asking reflection for it.

C# Finding the generated entry point

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

You will see a method whose name looks like <Main>$ declared on a class called Program, and a parameter of type String[] named args. The last detail matters: the variable args exists in every top-level program, even though you never declared it.

Rules for top-level statements

  • Only one file per project may contain top-level statements. That file is the program's entry file.
  • Types and namespaces must come after the statements. If you declare a class first and then write a statement below it, you get error CS8803: Top-level statements must precede namespace and type declarations.
  • Local variables and local functions declared at the top level are scoped to the generated Main; they are not visible inside your classes.
  • You can use await directly, which makes the generated entry point asynchronous (see below).
C# Types go after the statements

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Statements, then a local function, then the type, all in one file. If you move class Greeter above the first line, compilation fails; try it:

C# A type before the statements (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The compiler answers main.cs(6,1): error CS8803: Top-level statements must precede namespace and type declarations.

The explicit Main method

The traditional form puts the entry point in a class:

C# A classic Main method

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Requirements for Main: it must be static, its name is exactly Main (capital M), and it returns void, int, Task or Task<int>. It may take no parameters or one string[]. The class can have any name and any access; Program is the convention. If a project has top-level statements and a Main method, the statements win and the compiler warns CS7022: The entry point of the program is global code; ignoring 'App.Main(string[])' entry point. (Naming your own class Program next to top-level statements fails with CS0260, because the compiler already generated a Program class.)

When should you prefer an explicit Main?

  • Library-style or framework code where the class has a clear role and a team convention says so.
  • When you want an attribute on the entry class, or to control access modifiers.
  • Older projects: you will read a lot of code written before C# 9.

For everything else, top-level statements remove noise. Many real projects still use them for a tiny Program.cs that only builds and starts an application.

Command-line arguments

Whatever a user types after the program name arrives in the string array args. In a terminal, dotnet run -- Ada 36 gives args the two strings "Ada" and "36". They are always strings; convert them with int.Parse and friends (see Type Conversion). In our editor there are no arguments, so the array is empty, and that is itself a good thing to check for.

C# Handling a missing argument

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Always guard against missing arguments, or your program crashes on the first run without them.

Exit codes

When a program ends, it reports a number to the operating system: the exit code. By convention 0 means success and any other value means failure. Scripts, CI servers and shells all use it (echo $? on Linux and macOS, echo %ERRORLEVEL% on Windows).

There are three ways to set it:

  1. Return an int from Main, or write return 2; in top-level statements.
  2. Set Environment.ExitCode and finish normally.
  3. Call Environment.Exit(code), which ends immediately (skipping remaining code and finally blocks, so use it rarely).

If an exception escapes unhandled, the runtime crashes the process with a non-zero code and prints the exception.

C# Returning an exit code

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Two inputs fail, so the program returns 1. Our editor notes the non-zero exit; on your machine, a shell sees 1. Command-line tools use distinct codes for different failures (for example 2 for bad usage, 3 for a missing file) so scripts can react differently.

Do not use Environment.Exit as a shortcut for returning from a method. It tears down the whole process, skips finally blocks, and makes code hard to test. Return a value or throw an exception, and let the top of the program decide the exit code.

Asynchronous entry points

Many programs need to wait for something slow, like a web request or a file, without blocking. In C# that is done with async and await (the whole Async and Concurrency chapter is about it). The entry point can be asynchronous too.

With top-level statements you just use await; the compiler makes the generated Main return Task. With an explicit Main you declare async Task Main (or async Task<int> Main to return an exit code).

C# await at the top level

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The same program with an explicit async Main:

C# async Task Main

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Whichever you choose, the runtime waits for the returned Task to complete before the process exits. Never write async void Main; it is not allowed, and async void in general is dangerous (see Async Pitfalls).

From one file to a project

Our editor has exactly one file. A real program splits into many, usually one type per file, named after the type, grouped in folders that mirror namespaces. This is a read-only picture of a small project on disk:

TEXT
BankApp/
  BankApp.csproj          project file: target framework, packages
  Program.cs              top-level statements: the entry point
  Models/
    Account.cs            namespace BankApp.Models; class Account
    Transaction.cs
  Services/
    AccountService.cs

Program.cs typically stays tiny:

C#
// Program.cs  (read-only: needs several files and a project)
using BankApp.Models;
using BankApp.Services;

var service = new AccountService();
var account = new Account("Ada", 100m);
service.Deposit(account, 25m);
Console.WriteLine(account.Balance);
C#
// Models/Account.cs
namespace BankApp.Models;

public class Account(string owner, decimal balance)
{
    public string Owner { get; } = owner;
    public decimal Balance { get; set; } = balance;
}

Because only one file may hold top-level statements, Program.cs is that file, and every other file contains only type declarations. Splitting by type keeps files short and makes version-control diffs easy to read.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the compiler do with top-level statements?

    Top-level statements (C# 9) are placed in a compiler-generated entry point, and a variable named args is available just as in a hand-written Main.
  2. 2. Which signature is NOT a valid entry point?

    The name must be exactly Main, with a capital M. Lowercase main is just another method.
  3. 3. Where must type declarations go in a file with top-level statements?

    Putting a type before the statements gives error CS8803: Top-level statements must precede namespace and type declarations.
  4. 4. A program should signal failure to the operating system. What is the conventional way?

    Exit code 0 means success; any other value means failure. Return an int from Main, or set Environment.ExitCode.
  5. 5. A program run with no command-line arguments reads args[0]. What happens?

    args is an array, not null, and it is empty when nothing was passed. Check args.Length before indexing.

Summary

  • A program starts at its entry point. Since C# 9 you can write top-level statements and the compiler generates Program.<Main>$(string[] args).
  • Types and namespaces must follow the top-level statements; only one file per project may have them.
  • The classic static void/int/Task/Task<int> Main(string[] args) is still valid and common.
  • args holds command-line arguments as strings; it is empty, never null, when none are passed.
  • Exit code 0 means success. Return an int, set Environment.ExitCode, or (rarely) call Environment.Exit.
  • await works at top level; with an explicit Main use async Task or async Task<int>.
  • Real projects split types into files by folder and keep Program.cs tiny.

Next: Comments and XML Documentation shows how to explain your code to humans and tools.