Yesterday I thought that my journey in discovering possibilities of the ‘using’ keyword had ended, but further reading introduced me to a new .NET 6 feature: implicit (global) using directives.
You can enable this feature by adding a <ImplicitUsings>enable</ImplicitUsings>
setting inside a <PropertyGroup>
in your .csproj
file.
Remark: The project templates in the .NET 6 SDK include this setting by default
Enabling this feature will automatically generate a global usings file for you. You can see the generated file by looking inside the obj
folder that gets created when you build a project. In here you'll find a subfolder named for your build configuration(e.g. Debug, Release, ...) containing a net6.0 folder. Inside there you'll find a file called something like ExampleApp.GlobalUsings.g.cs.
The content of this file will look something like this:
The set of included namespaces changes according to the project type.
You can control what is generated inside this file by adding MSBuild Item Group. To add namespaces you should use the <Using Include />:
And to remove namespaces you can use <Using Remove />: