De-clutter namespaces in C# 10

Nitin Manju
3 min readMay 30, 2022
Photo by Mohammad Rahmani on Unsplash

C# 10 was released last year and it has introduced a host of new features. Below is a list of useful features specifically designed around the declarations of namespace that can help you tidy your code base.

Global namespaces

If you have a large code base, chances are, the file is already cluttered with using statements. C# 10 introduces global namespaces, which like the name suggests, can be declared globally and will be available across all the files in your project. The global modifier is used to achieve this as shown below:

global using <fully-qualified-namespace>;

example: global using System.Configuration;

Typically, you would declare all the global namespaces in a single file like GlobalUsings.cs and that should allow you to use the namespaces in each file within the project without explicitly writing the using statements.

Implicit namespaces

C# 10 allows you to clean up ‘using <namespace>’ statements even further with implicit namespaces. When enabled, you don’t have to write the ‘using <namespace>’ statement for commonly used namespaces like System, System.IO etc as they will be referred to implicitly in all the files within the project.

When combined with global namespaces, it will further reduce the number of ‘using <namespace>’ statements required in a C# file since the commonly used namespaces don’t have to be declared globally. However, it is not mandatory to combine them together.

This feature should be enabled by default for projects created using Visual Studio 2022 and .NET 6. However, to achieve this manually add the property ImplicitUsings and set it to enable in the project properties as shown below.

<PropertyGroup>
<!-- Other properties like OutputType and TargetFramework -->
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

File-scoped namespaces

C# 10 allows you to create namespaces inside a file in a declarative manner. A namespace declaration can simply be written as below:

Notice the ‘;’ after the namespace and the missing curly bracket enclosure. The code inside this file will be part of the declared namespace and this new namespace can be referred to in other C# files or globally.

Bonus: Sync Namespaces

This is a new Visual Studio 2022 feature and is not tied with C# 10.

Sync Namespaces should work on earlier versions of .NET and C#. Right Click on the Solution or Project File and you should find it as shown below:

If you have C# files which have been moved between folders and the namespaces are out of sync, this feature should come in handy to set the right namespace for each file based on the <ProjectName>.<FolderName> format.

This will especially come in handy when you are performing a migration of a legacy code base.

--

--