Why Doesn't have any Class in Program.cs in .NET Core 5?

Viewed 1115

I am trying to work with .NET 5 to update my information. So I started to review the eShopOnContainers-ServicesAndWebApps project here.

I have read its older versions (2.2 and 3.1) that is a rich sample with a lot of fantastic points. But here in .NET 5, at first glance, in Program.cs, I see a lot of methods and properties without any classes which I can't understand and make me confused. How can we have methods without class in a cs file?

1 Answers

It's a feature of C# 9: top-level statements

Top-level statements remove unnecessary ceremony from many applications.

Only one file in your application may use top-level statements. If the compiler finds top-level statements in multiple source files, it’s an error. It’s also an error if you combine top-level statements with a declared program entry point method, typically a Main method. In a sense, you can think that one file contains the statements that would normally be in the Main method of a Program class.

So you can now write a program that contains only this line of code:

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