Global Using Directive in C# 10 with net 6.0

Omer Ozulku
3 min readApr 27, 2022

--

With the release of C# 10 in November 2021, we started to research and learn about the new features that came with us.

Actually Layered architectures, solutions with too many projects, etc. After a while, writing plain code in it became a necessity.

For this reason, I think that an important attack has been made in writing plain code with C# 10. Or we can think of it this way, someone learning to code with C#10 will have a hard time reading code in lower versions.

Among the requirements for using C# 10, .net 6.0 and above versions and VS 2022 above are required.

Let’s see how to use Global Using, one of the beauties of C# 10;

While writing code, too many using statements were used that were repetitive within the classes.

Simple pre-C# 10 code block

With C# 10, the above example became as follows, and thus the code blocks started to look very plain. However, this is not a situation that prevents you from still writing code according to old C# versions. You can still write code using using statements or namespace declarations using parentheses.

Writing simple code block with C# 10

So how is this global using topic used or set? We can use 2 different methods for this. The first is the easy part, we add a class called globalusings.cs or whatever name you want to give into the project. Then, we write the using directives that we are using inside this class, but we provide the use of them in all classes by writing them globally in front of these using directives.

First Sample of Global Using

For the second Global using property, it is sufficient to write the following Using definitions between the <ItemGroup>…</ItemGroup> tag in the .csproj file of the application.

Second Sample of Global Using

When this definition is made, you will see that a file named ‘{project-name}.GlobalUsings.g.cs’ has been created in the ‘obj’ -> ‘Debug’ -> ‘net6.0’ directory of the application. If you browse the related file, you will see that all defined namespaces are added here globally. It is seen that it comes in undefined namespaces, as in the image on the side. This is because of the ImplicitUsings property defined within the <PropertyGroup>…</PropertyGroup> tag. If this feature is enabled, common namespaces for an application are added to the automatically generated global using class here by default. If it is disabled, it will be seen that the ones other than those defined by us are deleted.

--

--

Omer Ozulku

With the coding adventure that entered my life in 1999, life continues. Now life is just me and my 2 curls (daughter and darling)