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 which 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 .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,
  1. using System;  
  2.   
  3. namespace ConsoleAppTopLevelProgram  
  4. {  
  5. class Program  
  6.     {  
  7. static void Main(string[] args)  
  8.         {  
  9.             Console.WriteLine("Hello World!");  
  10.         }  
  11.     }  
  12. }  
In this code we specify the using declaratives, then the namespace, class and finally the Main method. This is the boiler plate code that is created for us. This might seem 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,
  1. using System;  
  2. 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 bigfeature, but it does simplify the process for 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 which make C# a much more friendly language to program in. Happy Coding!