New in .NET 5 – Top-level Statements

.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.


Was this article helpful? Share it with your friends:

Share on email
Share on facebook
Share on twitter
Share on reddit

1 thought on “New in .NET 5 – Top-level Statements”

Leave a Comment

Looking for more?

You have visited our site before, and we appreciate you!

If you found the tutorials helpful, enter your email address for more free C# tips and tricks.

Can't get enough C#?

Enter your email address for more free C# tutorials and tips.