Updating your project to use File Scoped Namespaces
File Scoped Namespace is a new feature of C# 10. The idea is to remove one level of indentation from source files when they contain only one namespace in it. The goal is to reduce horizontal and vertical scrolling and make the code more readable.
namespace MyProject
{
class Demo
{
}
}
// File Scoped Namespace
namespace MyProject;
class Demo
{
}
Most of the files have only one namespace, so File Scoped Namespaces should apply to most of the files. However, you don't want to update then manually one by one. The solution is to use Visual Studio or dotnet format
to update your project to use File Scoped Namespaces.
First, you need to use C# 10 or higher. You can set it explictly in the project properties:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<LangVersion>10</LangVersion>
</PropertyGroup>
</Project>
Then, you need to set your preference in the .editorconfig
file. If you don't have a .editorconfig
file, you can create one at the root of your solution:
[*.cs]
csharp_style_namespace_declarations=file_scoped:suggestion
Then, you can use Visual Studio to fix your code style. Be sure to select "Fix all occurrences in Solution" to fix all occurrences in one click.
Convert all namespace declarations to file scoped namespaces
Alternatively, you can use dotnet format
to fix your code style:
dotnet tool update --global dotnet-format
dotnet format MySolution.sln --severity info --diagnostics=IDE0161
Note that you can remove --diagnostics=IDE0161
to fix all code style issues.
#Additional resources
Do you have a question or a suggestion about this post? Contact me!