File Scoped Namespaces is a C# 10 feature that removes one level of indentation from source files that contain a single namespace. This reduces horizontal and vertical scrolling and makes code more readable.
C#
namespace MyProject
{
class Demo
{
}
}
C#
// File Scoped Namespace
namespace MyProject;
class Demo
{
}
Most files contain a single namespace, so File Scoped Namespaces can apply to most of your project. However, updating them manually one by one is impractical. Use Visual Studio or dotnet format to automate the conversion.
First, ensure you are using C# 10 or higher. You can set this explicitly in the project file:
csproj (MSBuild project file)
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<LangVersion>10</LangVersion>
</PropertyGroup>
</Project>
Next, set your preference in the .editorconfig file. If you do not have one, create it at the root of your solution:
.editorconfig
[*.cs]
csharp_style_namespace_declarations=file_scoped:suggestion
You can then use Visual Studio to apply the fix. Select Fix all occurrences in Solution to update every file at once.
Convert all namespace declarations to file scoped namespaces
Alternatively, you can use dotnet format to fix your code style:
Shell
dotnet tool update --global dotnet-format
dotnet format MySolution.sln --severity info --diagnostics=IDE0161
You can omit --diagnostics=IDE0161 to fix all code style issues at once.
#Additional resources
Do you have a question or a suggestion about this post? Contact me!