"Treat all warnings as errors except..." in Visual Studio

In Visual Studio, I can select the "Treat warnings as errors" option to prevent my code from compiling if there are any warnings. Our team uses this option, but there are two warnings we would like to keep as warnings.

There is an option to suppress warnings, but we DO want them to show up as warnings, so that won't work.

It appears that the only way to get the behavior we want is to enter a list of every C# warning number into the "Specific warnings" text box, except for the two we want treated as warnings.

Besides the maintenance headache, the biggest disadvantage to this approach is that a few warnings do not have numbers, so they can't be referenced explicitly. For example, "Could not resolve this reference. Could not locate assembly 'Data....'"

Does anyone know of a better way to do this?


Clarifying for those who don't see immediately why this is useful. Think about how most warnings work. They tell you something is a little off in the code you just wrote. It takes about 10 seconds to fix them, and that keeps the code base cleaner.

The "Obsolete" warning is very different from this. Sometimes fixing it means just consuming a new method signature. But if an entire class is obsolete, and you have usage of it scattered through hundreds of thousands of lines of code, it could take weeks or more to fix. You don't want the build to be broken for that long, but you definitely DO want to see a warning about it. This isn't just a hypothetical case--this has happened to us.

Literal "#warning" warnings are also unique. I often want to check it in, but I don't want to break the build.


Solution 1:

You can add a WarningsNotAsErrors-tag in the project file.

<PropertyGroup>
    ...
    ...
    <WarningsNotAsErrors>618,1030,1701,1702</WarningsNotAsErrors>
</PropertyGroup>

Note: 612 and 618 are both warnings about Obsolete, don't know the difference but the project i'm working on is reporting Obsolete with warning 618.

Solution 2:

/warnaserror /warnaserror-:618

Solution 3:

or more specifically, in your case:

/warnaserror /warnaserror-:612,1030,1701,1702

this should treat all warnings as errors except for the ones in your comma separated list

Solution 4:

In Visual Studio 2022 we have a new Project Properties UI which includes an editor for this.

Under Build | Errors and Warnings if you set Treat warnings as errors to All, then another property appears which allows you to exempt specific warnings from being treated as errors:

enter image description here

This will add the following property to your project:

<WarningsNotAsErrors>618,1030,1701,1702</WarningsNotAsErrors>