Movatterモバイル変換


[0]ホーム

URL:


Skip to main content

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Download Microsoft EdgeMore info about Internet Explorer and Microsoft Edge
Table of contentsExit focus mode

Top-level statements - programs withoutMain methods

  • 2025-07-01
Feedback

In this article

You don't have to explicitly include aMain method in a console application project. Instead, you can use thetop-level statements feature to minimize the code you have to write.

Top-level statements allow you to write executable code directly at the root of a file, eliminating the need for wrapping your code in a class or method.This means you can create programs without the ceremony of aProgram class and aMain method.In this case, the compiler generates aProgram class with an entry point method for the application. The name of the generated method isn'tMain, it's an implementation detail that your code can't reference directly.

Here's aProgram.cs file that is a complete C# program:

Console.WriteLine("Hello World!");

Top-level statements let you write simple programs for small utilities such as Azure Functions and GitHub Actions. They also make it simpler for new C# programmers to get started learning and writing code.

The following sections explain the rules on what you can and can't do with top-level statements.

Only one top-level file

An application must have only one entry point. A project can have only one file with top-level statements. Putting top-level statements in more than one file in a project results in the following compiler error:

CS8802 Only one compilation unit can have top-level statements.

A project can have any number of source code files that don't have top-level statements.

No other entry points

You can write aMain method explicitly, but it can't function as an entry point. The compiler issues the following warning:

CS7022 The entry point of the program is global code; ignoring 'Main()' entry point.

In a project with top-level statements, you can't use the-main compiler option to select the entry point, even if the project has one or moreMain methods.

using directives

For the single file containing top-level statementsusing directives must come first in that file, as in this example:

using System.Text;StringBuilder builder = new();builder.AppendLine("The following arguments are passed:");foreach (var arg in args){    builder.AppendLine($"Argument={arg}");}Console.WriteLine(builder.ToString());return 0;

Global namespace

Top-level statements are implicitly in the global namespace.

Namespaces and type definitions

A file with top-level statements can also contain namespaces and type definitions, but they must come after the top-level statements. For example:

MyClass.TestMethod();MyNamespace.MyClass.MyMethod();public class MyClass{    public static void TestMethod()    {        Console.WriteLine("Hello World!");    }}namespace MyNamespace{    class MyClass    {        public static void MyMethod()        {            Console.WriteLine("Hello World from MyNamespace.MyClass.MyMethod!");        }    }}

args

Top-level statements can reference theargs variable to access any command-line arguments that were entered. Theargs variable is never null but itsLength is zero if no command-line arguments were provided. For example:

if (args.Length > 0){    foreach (var arg in args)    {        Console.WriteLine($"Argument={arg}");    }}else{    Console.WriteLine("No arguments");}

await

You can call an async method by usingawait. For example:

Console.Write("Hello ");await Task.Delay(5000);Console.WriteLine("World!");

Exit code for the process

To return anint value when the application ends, use thereturn statement as you would in aMain method that returns anint. For example:

string? s = Console.ReadLine();int returnValue = int.Parse(s ?? "-1");return returnValue;

Implicit entry point method

The compiler generates a method to serve as the program entry point for a project with top-level statements. The signature of the method depends on whether the top-level statements contain theawait keyword or thereturn statement. The following table shows what the method signature would look like, using the method nameMain in the table for convenience.

Top-level code containsImplicitMain signature
await andreturnstatic async Task<int> Main(string[] args)
awaitstatic async Task Main(string[] args)
returnstatic int Main(string[] args)
Noawait orreturnstatic void Main(string[] args)

Beginning with C# 14, programs can befile based programs, where a single file contains the program. You runfile based programs with the commanddotnet run <file.cs>, or using the#!/usr/local/share/dotnet/dotnet run directive as the first line (unix shells only).

C# language specification

For more information, see theC# Language Specification. The language specification is the definitive source for C# syntax and usage.

Feature specification - Top-level statements

Collaborate with us on GitHub
The source for this content can be found on GitHub, where you can also create and review issues and pull requests. For more information, seeour contributor guide.

Feedback

Was this page helpful?

YesNo

In this article

Was this page helpful?

YesNo