What’s new in .NET 5 and C# 9?
In this section, we explore the following C# 9 features:
- Top-level statements
- Target-typed
new
expressions - Init-only properties
- Record classes
We use top-level statements to simplify code samples, leading to one code file with less boilerplate code. Moreover, top-level statements are the building blocks of the .NET 6 minimal hosting model and minimal APIs. We dig into the new
expressions, which allow creating new instances with less typing. The init-only properties are the backbone of the record classes used in multiple chapters and are foundational to the MVU example presented in Chapter 18, A Brief Look into Blazor.
Top-level statements
Starting from C# 9, it is possible to write statements before declaring namespaces and other members. Those statements are compiled to an emitted Program.Main
method.
With top-level statements, a minimal .NET “Hello World” program now looks like...