New in .NET 5 - Top-level Statements

NEW IN .NET 5: TOP-LEVEL STATEMENTS. GOOD NEWS FOR BEGINNERS

by

.NET 5.0 is here. The next major release of .NET Core has launched, and with it comes some significant changes. In this post, we will be highlighting one of those changes that is making headlines.

Top-Level Statements

The launch of C# 9 (alongside the .NET 5 release) brings some new features to the language, and one of those is the adoption of top-level statements. In other words, the Main() method and surrounding namespace and program class details are no longer required.

To get started, configure your project to target .NET 5 from your project's property settings.

With the project properly configured to take advantage of this new feature, let's consider the following example taken from the beginner tutorial series.

using System;
 
namespace HelloFromWellsb
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello from wellsb.com!");
            Console.ReadLine();
        }
    }
}

Thankfully, the code above is still valid code in C# 9, but this program can also be dramatically simplified by writing it using top-level statements. In this case, the following code is an equally valid C# program that will produce the same output as the code above.

using System;
 
Console.WriteLine("Hello from wellsb.com!");
Console.ReadLine();

What is the point?

There are many exciting features in C# 9 and .NET 5.0, but this one has rightfully received a lot of press. The lighter syntax helps remove a barrier to adoption that may otherwise deter new developers who are trying to decide on a programming language. A Hello World program in C# can now be written using a single line of code, like with Python and other compact-syntax languages.

To be clear, more complex .NET applications will still benefit from explicitly defining the Main() method within a given program class and with a specific namespace. The beauty is that the complexities that make C# such a robust language are still fully available. Yet, the added ability to simplify C# code by allowing statements at the top-level of a program has the potential to entice new developers into the .NET ecosystem.


Don't stop learning!

There is so much to discover about C#. That's why I am making my favorite tips and tricks available for free. Enter your email address below to become a better .NET developer.


Did you know?

Our beautiful, multi-column C# reference guides contain more than 150 tips and examples to make it even easier to write better code.

Get your cheat sheets