Top Level Programs In C# 9.0

Introduction

In today’s article we will look at top-level programs in C# 9.0. C# 9.0 has been introduced with .NET 5.0. We will look at another cool feature that C# 9.0 brings to us, which is top-level programs and how to use them.

Using C# 9.0

Microsoft recently announced the availability of a .NET 5 release candidate at Microsoft Ignite 2020. This included the latest features in C# 9.0. In order to code in .NET 5.0, we would need to install the latest preview of Visual Studio 2019 (Version 16.8.0 Preview 6.0). As I had read about some cool features in C# 9.0, including the use of top-level programs, I downloaded and installed the required version as below,

Top Level Programs In C#

Using Top-Level Programs

Let us create a console application in Visual Studio 2019 (Version 16.8.0 Preview 6.0) as below,

Top Level Programs In C#

Top Level Programs In C#

Top Level Programs In C#

Now, we see the below code,

using System;

namespace ConsoleAppTopLevelProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
        }
    }
}

In this code, we specify the using declarative, then the namespace, class, and finally the Main method. This is the boilerplate code that was created for us. This might seem like a lot for a program that just needs to write Hello World! on the screen. Previously we had to use this template. Now with C# 9.0, we can reduce this code.

Let us change our target framework to .NET 5.0 as below,

Top Level Programs In C#

We can now modify the code as below,

using System;
Console.WriteLine("Hello World!");

When we run the program, we get the same result as below,

Top Level Programs In C#

Behind the scenes, the static class and main methods are generated. This might not seem like a noticeably big feature, but it does simplify the process of creating small programs and is very convenient for new language learners.

Summary

In this article, we looked at using top-level programs in C# 9.0. We could say that this is not an incredibly significant change. However, these are the new changes that make C# a much more friendly language to program in. Happy Coding!


Recommended Free Ebook
Similar Articles