IDE0005 as Build Error
12/21/2023
2 minutes
I recently set up the IDE0005 .editorconfig file rule to break the CLI build. This is an IDE rule, that normally is not emitted as warnings / errors in the CLI build.
IDE0005 rule flags unnecessary using directives. It wraps CS8019
that also does the same.
Setup
Add an .editorconfig
file containing the rule and set the severity as a warning. It may be also set as an error if one prefers to get a build error without setting warnings to break builds.
[*.cs] dotnet_diagnostic.IDE0005.severity = warning
To make it effective we need to set two further property group flags that are detailed in this GitHub issue:
<GenerateDocumentationFile>true</GenerateDocumentationFile> <EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
With these settings the warnings/errors are emitted during build CLI build and not just in the IDE.
Multiple Projects
Instead of settings these two msbuild properties on every project in a larger solution, I set them in a Directory.Build.props
and Directory.Build.targets
files.
There are multiple ways to set msbuild properties, but in this blog post, I will focus on the Directory.Build.*
option to have a greater control over which projects enforce the above rule. More specifically, I would like to avoid test projects to enforce IDE0005 rule.
To achieve this, one could organize all test projects under a single folder that has a folder level Directory.Build.props
file with disabling the rules. However, this is not always possible in existing solutions where test projects are separated into different folders.
An alternative approach is to set <GenerateDocumentationFile>true</GenerateDocumentationFile>
in Directory.Build.props
file and set the following snippet in Directory.Build.targets
file.
<PropertyGroup Condition="'$(IsTestProject)' != 'true'"> <EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild> </PropertyGroup>
This way the emitting the compiler flag is protected with a condition that check another property's value.
Finally flag the unit test csproj-s with <IsTestProject>true</IsTestProject>
property. With such a generic flags one can control the build properties for test projects in a single file even when these projects are not under a dedicated folder.