New in C# 10: File Scoped Namespaces

04/09/2021 dotnet c#

With .Net 6 in preview, it's time to look forward to the new version of C# 10 we'll see released later this year. One new feature that is designed to reduce unnecessary space is file scoped namespaces. Let's have a look...

This is the second part in this series, also check out New in C# 10: Global Usings.

As with many of the recent changes in C#9 and upcoming C#10, this change is designed to reduce "noise" in our code and make C# more readable. If you have written C#, you will recognise the format for defining the namespace our code is in:

namespace X.Y.Z

{

    //more code

}

We need this around all of our classes before we have anything else written we have atleast 4 lines of code. With file scoped namespaces, we can have the namespace defined without the need for the scoped braces:

namespace X.Y.Z;

//more code

Here is an example from an Umbraco v9 project (running on .Net 6 preview):

Here is the same code in C# 9 without the file scoped namespace:

Notice the extra lines of code and braces that are required in C# 9 to do the same. Of course, this very simple example doesn't reduce that many lines of code or many tabs of indentation on our class. However, this combined with the many other changes to C# with the goal of simplifying can reduce class' complexity. For example, global usings and top level programs.

The .Net 6 default templates have been updated to use these new conventions. Here is the Program.cs for a new ASP.Net Core API project in .Net 6. You'll notice it uses file scoped namespaces aswell as top level programs.

Compare this to the C#9 version of this template that requires a Program.cs and Startup.cs. What do you think? I personally like the readability of the C# 10 version and the lack of unnecessary indentation.

To learn more, check out the C# language specifications for more information: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-10.0/file-scoped-namespaces 

C#10 and .Net 6 will be released in November 2021.