Last week I had a pair programming session with a candidate. The candidate had a background in C and was new to C#. While he was writing some code, he was struggling with namespaces in C#. It even got me confused as I completely forgot that C# 10 introduced a new feature 'file scoped namespaces'.
I always had written namespaces in any of the following ways:
The advantage of this approach is that you could have multiple namespaces in one file. But in reality I think I never used this possibility. The disadvantage is that traditional namespaces add some extra ceremony to your code.
C# 10 gets rid of this boilerplate code when you want to use only one namespace per file. So the example above can be rewritten as:
All the types we write in this file will be part of the X.Y.Z
namespace.
Update your existing code
To update your existing code in one go, you can use the dotnet format tool:
dotnet tool update --global dotnet-format
dotnet format Example.sln --severity info --diagnostics=IDE0161