Namespace in C# 10

Gal Ilinetsky
CodeX
Published in
2 min readOct 30, 2022

Namespaces are heavily used in C# for two reasons:

  • .NET uses namespaces to organize its many classes.
  • Control the scope of class and method names in larger programming projects.

Here is an example of declaring a namespace and using it and other .Net namespaces with the using keyword:

In C# 10 we are introduced to a few features regarding the namespace and the using practice. Here they are:

Global using statements

When our code uses a class from a different namespace we need to declare the use of this namespace at the beginning of the file. This can cause us to declare the same namespace over and over again in many files in our project. Global using statement's main benefit is that we are now able to avoid the clutter of declaring namespaces over and over (things like using System etc.) in every single file. Instead, we can create on cs file with all the namespaces (or some of them) we are using in our project, and prevent them from declaring at any other file.

This is how the same code will look now:

File with all declared namespaces we use

File scoped namespaces

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

If you will look closely at the original ProductInfoProvider.cs and the one after the change, you will see the use of this feature:

original

namespace Product.Providers
{
public class ProductInfoProvider
{

}
}

scoped namespace

namespace Product.Providers;
public class ProductInfoProvider
{
}

Implicit global usings

This feature creates a hidden auto-generated file that declares global using statements. You can see the file under obj folder, the file name is in the format <ProjectName>.GlobalUsings.g.cs

This feature is turned on by adding <ImplicitUsings>enable</ImplicitUsings> to the csproj file.

Please notice that this feature will auto-generate global using statements for specific namespaces depend on the project type.

In conclusion, these new features are not game-changers, but we can use them to remove some boilerplate code.

--

--

Gal Ilinetsky
CodeX
Writer for

Software Engineer, .net development focus. Here to share my knowledge on points of view on software development fields I take interest in.