In C# 9.0, top-level statements are syntax features that allow developers to write code directly at the top of the file. Without the need for a class and methods. This feature was introduced in November 2020 as part of .NET 5.
Before C# 9.0, every C# program required an entry point, the Main method, defined within a class like this:
csharpusing System; namespace HelloWorld { class Program { static void Main(string[] args) { Console.WriteLine("Hello, World!"); } } }
Although the above code is obvious, it includes boilerplate rules. Using top-level statements, you can skip the Main path and write your program logic directly at the top of the file.
csharp// Top-level statements in C# 9.0 using System; Console.WriteLine("Hello, World!");
You can simplify the code by using the top-level statements. It can reduce code by removing the Main method and its associated class.
Top-level statements are important for simplifying smaller applications, such as Azure Functions and GitHub Actions.
Top-level statements are not well structured so they might not be suitable for large or complex apps that need more structure.
Top-level statements can only be used in one file per project, usually Program.cs.
The compiler generates a Program class with an entry point method for the application, but the method name is not Main.
Top-level statements are optional so that, developers can choose whether or not to use them.
With top-level statements, the compiler generates the main method for you. You simply write your code as if you were inside the body of the main method, and the compiler takes care of the rest.
Let’s create the example by reading command-line arguments using top-level statements:
csharpusing System; class Program { static void Main(string[] args) { if (args.Length > 0) { Console.WriteLine($"Hello, {args[0]}!"); } else { Console.WriteLine("Hello, World!"); } } }
Output
csharpusing System; if (args.Length > 0) { Console.WriteLine($"Hello, {args[0]}!"); } else { Console.WriteLine("Hello, World!"); }
Output
Here, args are still available, even though we have not explicitly defined the Main method. The compiler automatically sends the command line to top-level statements.
Top-level statements also work with asynchronous code. For asynchronous tasks, simply mark the top-level entry as async:
csharpusing System; using System.Threading.Tasks; class Program { static async Task Main(string[] args) { await PrintMessageAsync(); } static async Task PrintMessageAsync() { await Task.Delay(1000); Console.WriteLine("Async operation completed."); } }
Output
With top-level statement
csharpusing System; using System.Threading.Tasks; await Task.Delay(1000); Console.WriteLine("Async operation completed.");
Output
Again, we notice how concise the code becomes. The async keyword applies to the automatically generated main method.
Copyrights © 2024 letsupdateskills All rights reserved