Top-level statements, global usings and file-scoped namespaces
suggest changeThis is what Program.cs used to look like:
using System;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
}
}
}
And this is what dotnet new console creates today:
Console.WriteLine("Hello, World!");
Three features remove the extra lines:
- Top-level statements (C# 9, .NET 5): code written directly in a file, with no
class Programand noMain. - Global usings (C# 10, .NET 6):
global using X;applies to every file in the project. With<ImplicitUsings>enable</ImplicitUsings>the SDK adds the common ones for you, which is whyConsoleworks withoutusing System;. - File-scoped namespaces (C# 10):
namespace X;instead ofnamespace X { ... }, so a file's code isn't indented one extra level.
C# 11 added a related feature, file-local types (file class Helper), which are visible only inside the file that declares them.
All examples were built and run with the .NET 10 SDK (C# 14) as a normal console project (dotnet new console). If you'd rather skip the project file entirely, see "File-based programs" in C# Interactive. Top-level statements and implicit usings work the same way there.
The default console project
$ dotnet new console -n Hello
The project file:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
And Program.cs is one line:
Console.WriteLine("Hello, World!");
If you want the old layout with a Program class and a Main method, ask for it:
$ dotnet new console -n Classic --use-program-main
namespace Classic;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
}
}
That template still uses a file-scoped namespace and implicit usings, so there's no using System; at the top.
See Creating a new program using .NET Core for the older project format.
Top-level statements
args, exit codes and await
Top-level code works like the body of Main:
argsis available as astring[]. You don't declare it.return 1;sets the process exit code.awaitworks directly. You don't needasync Task Main.
using System.Reflection;
Console.WriteLine($"args: {args.Length} [{string.Join(", ", args)}]");
MethodInfo entry = Assembly.GetEntryAssembly()!.EntryPoint!;
Console.WriteLine($"class: {entry.DeclaringType}");
Console.WriteLine($"method: {entry}");
if (args.Length == 0)
{
Console.Error.WriteLine("usage: hello <name>");
return 1;
}
await Task.Delay(100);
Console.WriteLine($"Hello, {Greeter.Shout(args[0])}");
return 0;
static class Greeter
{
public static string Shout(string s) => s.ToUpperInvariant() + "!";
}
$ dotnet run
args: 0 []
class: Program
method: Int32 <Main>(System.String[])
usage: hello <name>
$ echo $?
1
$ dotnet run -- ada lovelace
args: 2 [ada, lovelace]
class: Program
method: Int32 <Main>(System.String[])
Hello, ADA!
$ echo $?
0
Arguments after -- are passed to the program, not to dotnet run.
What the compiler generates
The compiler wraps the statements in a method called <Main>$, inside an internal class called Program. Neither name can be written in C#, so other code can't call the entry point by accident.
Its return type depends on what the code uses:
| Top-level code contains | Generated method |
|---|---|
no await, no return value |
void <Main>$(string[] args) |
return 0; |
int <Main>$(string[] args) |
await |
Task <Main>$(string[] args) |
await and return 0; |
Task<int> <Main>$(string[] args) |
Each row was checked with reflection. For the async versions the compiler also emits a small synchronous <Main> method that waits for the task. That's the method the runtime calls, and it's what EntryPoint reported in the previous example.
Local functions, types and the Program class
A file with top-level statements can also contain:
- local functions: they're local to the generated
<Main>$, so they can use the top-level variables - type declarations (classes, records, enums, ...), which must come after all the statements
- a
partial class Programthat adds members to the generated class
using System.Reflection;
int count = 3;
Console.WriteLine(Twice(count));
Console.WriteLine(Program.Version);
var flags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly;
foreach (var m in typeof(Program).GetMethods(flags))
Console.WriteLine($" {m}");
Console.WriteLine($"public class? {typeof(Program).IsPublic}");
await Task.Yield();
int Twice(int x) => x * 2;
partial class Program
{
public static string Version => "1.2.0";
}
6
1.2.0
System.Threading.Tasks.Task <Main>$(System.String[])
System.String get_Version()
Void <Main>(System.String[])
Int32 <<Main>$>g__Twice|0_0(Int32)
public class? False
Twice is compiled as a static method with a generated name. count is a local variable, not a field.
The generated Program class is internal. That matters for ASP.NET Core integration tests, where WebApplicationFactory<Program> in a test project needs a public Program. The usual fix was one line at the end of Program.cs:
public partial class Program { }
Starting with .NET 10, the Web SDK (Microsoft.NET.Sdk.Web) generates that line for you. The same one-line program built with the two SDKs prints:
Console.WriteLine($"Program is public: {typeof(Program).IsPublic}");
Microsoft.NET.Sdk -> Program is public: False
Microsoft.NET.Sdk.Web -> Program is public: True
Rules and errors
Only one file can have top-level statements. Add a second one and you get:
error CS8802: Only one compilation unit can have top-level statements.
Statements come first. A type declared before the statements is an error:
class Early { }
Console.WriteLine("main");
error CS8803: Top-level statements must precede namespace and type declarations.
Top-level variables are locals. Types declared in the same file can't see them:
string greeting = "hi";
Console.WriteLine(greeting);
class Helper2
{
public static void Say() => Console.WriteLine(greeting);
}
error CS8801: Cannot use local variable or local function 'greeting' declared in a top-level statement in this context.
To share a value with other types, put it in a static member, for example in a partial class Program or in a separate static class.
Top-level statements win over Main. If the project also has a static void Main, the compiler warns and ignores it:
warning CS7022: The entry point of the program is global code; ignoring 'Old.Main()' entry point.
No file-scoped namespace in Program.cs. namespace MyApp; followed by statements doesn't compile, because statements can't be inside a namespace. The generated Program is always in the global namespace. You can still declare a block namespace after the statements:
Console.WriteLine(MyApp.Util.Name);
namespace MyApp
{
static class Util { public static string Name => "util"; }
}
util
In practice, keep Program.cs for startup code and put types in their own files with a file-scoped namespace.
When to use top-level statements
They work well for console tools, small utilities, samples, and ASP.NET Core's Program.cs, which is mostly builder.Services.Add... and app.Map... calls anyway.
Prefer an explicit Main when:
- The entry point is complex enough that you want ordinary private methods and fields next to it.
- A tool or framework you use looks for a named
Mainmethod. - Your team simply finds the explicit version easier to read. Both compile to the same thing.
Global usings
global using
A global using directive works like a normal using, but applies to every file in the project. Every form of using can be made global: namespaces, using static, and aliases (including the C# 12 alias for any type, here a tuple):
// GlobalUsings.cs
global using System.Text.Json;
global using static System.Math;
global using Point = (int X, int Y);
// Program.cs
Point p = (3, 4);
double length = Sqrt(p.X * p.X + p.Y * p.Y);
Console.WriteLine(JsonSerializer.Serialize(new { p.X, p.Y, length }));
{"X":3,"Y":4,"length":5}
The file name doesn't matter, but a single GlobalUsings.cs (or Usings.cs) is the usual convention, so readers know where to look.
Two placement rules:
using System.Text;
global using System.Diagnostics;
error CS8915: A global using directive must precede all non-global using directives.
namespace N
{
global using System.Diagnostics;
}
error CS8914: A global using directive cannot be used in a namespace declaration.
For ordinary using, using static and aliases, see Using Directive, Access Static Members of a Class and Using alias directives.
ImplicitUsings: what each SDK imports
With <ImplicitUsings>enable</ImplicitUsings> in the project file, the SDK writes a file obj/Debug/net10.0/<Project>.GlobalUsings.g.cs and compiles it with your code. For a console app (Microsoft.NET.Sdk) it contains:
// <auto-generated/>
global using System;
global using System.Collections.Generic;
global using System.IO;
global using System.Linq;
global using System.Net.Http;
global using System.Threading;
global using System.Threading.Tasks;
Other SDKs add their own namespaces. These lists come from the generated files in a .NET 10 build:
| SDK | Adds on top of the console list |
|---|---|
Microsoft.NET.Sdk (console, class library) |
(the base list above) |
Microsoft.NET.Sdk.Web (ASP.NET Core) |
System.Net.Http.Json, Microsoft.AspNetCore.Builder, Microsoft.AspNetCore.Hosting, Microsoft.AspNetCore.Http, Microsoft.AspNetCore.Routing, Microsoft.Extensions.Configuration, Microsoft.Extensions.DependencyInjection, Microsoft.Extensions.Hosting, Microsoft.Extensions.Logging |
Microsoft.NET.Sdk.Worker (background services) |
Microsoft.Extensions.Configuration, Microsoft.Extensions.DependencyInjection, Microsoft.Extensions.Hosting, Microsoft.Extensions.Logging |
That's why WebApplication.CreateBuilder(args) compiles in a fresh web project without a single using line. The Worker SDK expects the Microsoft.Extensions.Hosting package, which the dotnet new worker template references.
Turn it off and you're back to writing usings yourself:
<ImplicitUsings>disable</ImplicitUsings>
Console.WriteLine(Path.GetExtension("a.txt"));
error CS0103: The name 'Console' does not exist in the current context
error CS0103: The name 'Path' does not exist in the current context
Projects upgraded from .NET Framework or .NET Core 3.1 usually don't have the property, so implicit usings are off for them until you add it.
Using items in the project file
You can change the generated list from the project file with <Using> items, without writing any C#:
<ItemGroup>
<Using Include="System.Text.Json" />
<Using Include="System.Console" Static="true" />
<Using Include="System.Text.RegularExpressions.Regex" Alias="Re" />
<Using Remove="System.Net.Http" />
</ItemGroup>
var words = Re.Split("one, two;three", @"[,;]\s*");
WriteLine(JsonSerializer.Serialize(words));
["one","two","three"]
The generated file now reads:
// <auto-generated/>
global using System;
global using System.Collections.Generic;
global using System.IO;
global using System.Linq;
global using System.Text.Json;
global using System.Threading;
global using System.Threading.Tasks;
global using Re = System.Text.RegularExpressions.Regex;
global using static System.Console;
Includeadds a namespace.Static="true"producesglobal using static.Alias="Re"producesglobal using Re = ....Removedrops one of the SDK defaults. A common reason is a name clash between one of your types and a type in that namespace.
Put the items in a Directory.Build.props file to share them across every project in a repository. Test projects often do this to import Xunit or NUnit.Framework everywhere.
Global usings: cautions
- Hidden dependencies. A file that compiles in one project may not compile when copied to another, because it relied on a global using it doesn't show. Keep the global list short and obvious: framework namespaces, plus the main namespace of your own project.
- Ambiguities. Each global namespace brings in all of its type names. If two global namespaces define the same name (both
System.ThreadingandSystem.Timershave aTimer), every file that uses the name gets an ambiguity error, not only the file that caused it. - Find the list. If you're unsure what's in scope, look at
obj/.../*.GlobalUsings.g.csand search the project forglobal using.
File-scoped namespaces
Syntax
A file-scoped namespace declaration ends with ; and applies to everything that follows in the file:
// Billing/Invoice.cs
namespace Shop.Billing;
public record Invoice(string Customer, decimal Amount)
{
public string Format() => $"{Customer}: {Amount:0.00}";
}
public static class Tax
{
public static decimal Add(decimal amount) => amount * 1.2m;
}
// Program.cs
using Shop.Billing;
var inv = new Invoice("Ada", Tax.Add(100m));
Console.WriteLine(inv.Format());
Console.WriteLine(typeof(Invoice).FullName);
Ada: 120.00
Shop.Billing.Invoice
The result is the same as namespace Shop.Billing { ... }. The only difference is that the file loses one level of indentation and a closing brace. Most files contain a single namespace anyway, so this fits nearly every file. Namespaces themselves are explained in Namespaces.
Rules
A file can have only one file-scoped namespace, it can't be mixed with block namespaces, and it must come before any type:
error CS8954: Source file can only contain one file-scoped namespace declaration.
error CS8955: Source file can not contain both file-scoped and normal namespace declarations.
error CS8956: File-scoped namespace must precede all other members in a file.
using directives can go before or after the declaration. A using placed after namespace X; is inside the namespace, just as if it were inside the braces of a block namespace. This affects how names are resolved, and some style guides require it.
Converting an existing code base
Set the preferred style in .editorconfig:
[*.cs]
csharp_style_namespace_declarations = file_scoped:warning
Then let dotnet format rewrite every file (IDE0161 is the "use file-scoped namespace" rule):
$ dotnet format style --diagnostics IDE0161
A file like this:
namespace Shop.Legacy
{
public class Customer
{
public string Name { get; set; } = "";
}
}
becomes:
namespace Shop.Legacy;
public class Customer
{
public string Name { get; set; } = "";
}
Visual Studio and Rider can do the same with a quick fix applied to the whole solution.
file-local types
C# 11 added the file modifier for types. A file class (or struct, record, interface, enum, delegate) can be used only in the source file that declares it. Two files can therefore each have their own private helper with the same name:
// Report/Csv.cs
namespace Report;
public static class Csv
{
public static string Row(params string[] cells) =>
string.Join(",", cells.Select(Escaper.Escape));
}
file static class Escaper
{
public static string Escape(string s) =>
s.Contains(',') || s.Contains('"') ? $"\"{s.Replace("\"", "\"\"")}\"" : s;
}
// Report/Html.cs
namespace Report;
public static class Html
{
public static string Cell(string s) => $"<td>{Escaper.Escape(s)}</td>";
}
file static class Escaper
{
public static string Escape(string s) =>
s.Replace("&", "&").Replace("<", "<").Replace(">", ">");
}
// Program.cs
using Report;
Console.WriteLine(Csv.Row("Ada", "London, UK", "say \"hi\""));
Console.WriteLine(Html.Cell("a < b & c"));
var t = typeof(Csv).Assembly.GetTypes().Where(t => t.Name.Contains("Escaper"));
foreach (var type in t)
Console.WriteLine(type.FullName);
Ada,"London, UK","say ""hi"""
<td>a < b & c</td>
Report.<Csv>F472E92926DDB716E0566001CBB748CDA421F399C39579705EC47174C3C5449A4__Escaper
Report.<Html>F7FDDF44F54F1BE0E762DD885BE02980F0C82066585DE30A68CB53BBBFBBD96CC__Escaper
Both Report.Escaper classes exist without a name clash, because the compiler gives each one a unique name built from the file name and a hash.
Other files can't see them:
// Program.cs
Console.WriteLine(Report.Escaper.Escape("x"));
error CS0234: The type or namespace name 'Escaper' does not exist in the namespace 'Report' (are you missing an assembly reference?)
A file-local type also can't appear in the signature of a type that is visible outside the file:
namespace Report;
file record Options(bool Pretty);
public static class Leak
{
public static Options Default() => new(false);
}
error CS0050: Inconsistent accessibility: return type 'Options' is less accessible than method 'Leak.Default()'
error CS9051: File-local type 'Options' cannot be used in a member signature in non-file-local type 'Leak'.
file is narrower than private (which only works for nested types) and internal (visible to the whole assembly). It's used heavily by source generators, which can emit helper types without worrying about clashing with user code or with another generator's output. In your own code it's a good fit for small helpers that only make sense next to the class that uses them.
Summary
| Feature | Version | What it removes |
|---|---|---|
| Top-level statements | C# 9 / .NET 5 | class Program and static void Main |
global using |
C# 10 / .NET 6 | repeated using lines in every file |
<ImplicitUsings>enable</ImplicitUsings> |
.NET 6 SDK | even the global usings for common framework namespaces |
<Using Include/Remove> in csproj |
.NET 6 SDK | a GlobalUsings.cs file |
File-scoped namespace X; |
C# 10 | one level of braces and indentation |
file types |
C# 11 | name clashes between private helpers in different files |
None of them changes what the program does at run time: they only change how much code you have to write and read.