preamble
A new feature was introduced in the C# 9 release:top-level statement
This feature allows you to write code directly without explicitly defining the Main method.
The traditional way of writing
namespace TestStatements
{
internal class Program
{
static void Main(string[] args)
{
foreach (var arg in args)
{
(arg);
}
("Hello, time chasers!") )
}
}
}
Top-level statement writing
foreach (var arg in args)
{
(arg);
}
("Hello, time chasers!") )
Advantages of top-level statements
- The Main method and namespace declarations are omitted, making the code more concise.
- Particularly suitable for writing simple console applications, scripts and demo code.
- For beginners, you don't need to know too many complex syntax structures to start writing C# programs.
Shortcomings of top-level statements
- Top-level statements are better suited for simple programs; for large, complex projects, the traditional Main methods and namespaces are still necessary.
- For developers accustomed to traditional structures, top-level statements may make the organization of the code seem unclear.
- This may lead to compatibility issues if mixed with other C# versions or with some specific project structures.
final conclusion
Top-level statements reduce the learning curve and increase development efficiency by simplifying the code structure, making them particularly suitable for beginners and for scenarios where simple programs are written. However, in large projects, traditional code structure is still necessary. Therefore, top-level statements and traditional methods each have their own scenarios and advantages, and developers can choose which one to use according to their specific needs. Personally, I prefer the traditional way of writing, it looks more intuitive and the code is well organized.
reference article
- /zh-cn/dotnet/csharp/fundamentals/program-structure/top-level-statements