DEV Community

Juarez Júnior for Develop4Us

Posted on • Edited on

C# Tip: Top-level Statements

Let’s talk about Top-level Statements, introduced in C# 9, which allow you to write code directly at the top level of a file, without needing to encapsulate it within a class or Main method. See the example in the code below.

Console.WriteLine("Hello, world!");
int result = Add(5, 10);
Console.WriteLine($"The result of the addition is: {result}");

int Add(int a, int b)
{
    return a + b;
}
Enter fullscreen mode Exit fullscreen mode

Explanation:

With Top-level Statements, you can simplify the structure of your program, especially in small scripts or demonstration programs. Before C# 9, all code had to be inside a class with a Main method, but now you can write the code directly at the top level of the file, making it more concise and readable, particularly for small examples or quick prototypes.

This feature is especially useful for small projects, scripts, or when working with code examples for learning, as it removes boilerplate code that might distract from the main focus.

Source code: GitHub

I hope this tip helps you use Top-level Statements to simplify your smaller projects or code examples! Until next time.

Top comments (0)