This article is part of C# Advent 2022. During the month of December, two new articles are posted each day until December 25th. These articles will be about something in the C# language, and are written by experts from around the C# community.
Trailhead is proud to be a part of it this year!
What are Top-Level Statements?
Top-level statements in C# are a feature that allows developers to write code directly at the root of a file, without having to wrap it in a class or a method. This was introduced in C# 9.0, which was released in November 2020 as part of .NET 5.
Before C# 9.0, if you wanted to write code in a C# file, you had to wrap it inside a class and a method. This often resulted in a lot of boilerplate code, especially for small scripts or simple programs. With the introduction of top-level statements, C# developers can now write code directly at the root of a file, without having to worry about creating classes or methods.
Top-Level Statements by Example
Before top-level statements, a simple console application in C# might look like this:
using System;
namespace Application
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
Now we can take advantage of top-level statements and write this same console application in just one line of code:
Console.WriteLine("Hello, World!");
The History of Top-Level Statements
Microsoft added top-level statements to C# to make it easier for developers to write simple programs and scripts. This is especially useful for those who are new to C#, as it reduces the amount of boilerplate code that needs to be written. It also makes C# more similar to other popular scripting languages like Python, which allows developers to more easily switch between languages.
Where You’ll Encounter Top-Level Statements
Besides consoles applications like the example above, another popular use of top-level statements in C# code today is the startup code for ASP.NET Core. The startup code is used to configure the application, set up middleware, and handle requests and responses. In the past, this code had to be in a Startup class. Now developers are able to write more concise and readable code, and makes it easier to get started with ASP.NET Core.
Here’s an example of the old Startup.cs file format from a .NET 5 MVC project:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace aspnet
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
And here’s what an MVC project’s startup code in Program.cs looks like in .NET 7 with top-level statements.
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
Notice how the new format is lot more compact!
Summing Up
Overall, top-level statements have been a valuable addition to C# which makes it easier for developers to write simple programs and scripts, and to get started quickly with console applications or ASP.NET Core apps. They provide an important tool in the C# developer’s toolkit, and will likely become increasingly popular as more developers discover their benefits.
If you’d like to learn more about top-level statements in C#, you can check out the Microsoft Learn documentation about it.