The top-level statements are a feature introduced in C# 10. The idea is to reduce the boilerplate code needed to define aplication’s entry point. So instead of the traditional:
using System;
namespace Application
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
Code language: C# (cs)
We can write the code directly in the main project’s file, which reduces the code to just one line:
Console.WriteLine("Hello, World!");
Code language: JavaScript (javascript)
.NET 6 templates use this new, concise form by default. But I find it rather confusing to have one file in a project follow different syntax rules or conventions. I see the traditional way as simpler, even if a bit more verbose. So how to fastest convert between one form and another?
Hopefully, if you have ReSharper 2022.2, there is an automatic conversion available, albeit a bit hard to discover. It seems to appear when you place your cursor on… an empty like in the Program.cs
file with top-level statements, and click the hammer icon, or press Alt+Enter:
When selected, the conversion works just fine:
The reverse action, transforming Program.cs
class into the compact form, is similarly available. This one is a bit easier to find: it’s in the line where the Program
class starts.
No comments yet, you can leave the first one!