Compiler warnings can be an indication of potential problems in your code project. For this reason it can be good practice to treat all warnings as errors.
Enabling treat warnings as errors can be set in the .NET project file directly. For example:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<NoWarn>CS1591</NoWarn>
</PropertyGroup>
</Project>
The TreatWarningsAsErrors
element allows us to enable or disable the treating of warnings as errors. If true
then any warnings will become errors and will fail compilation. If false
then warnings will remain as just warnings and will not fail compilation.
The NoWarn
element allows us to tell the compiler to not report certain warnings on compilation. In the example above warning CS1591
which reports missing XML comments on public types or members is being suppressed. The element can accept multiple warning numbers as a CSV string (<NoWarn>CS1591, CS1592</NoWarn>
etc.).
Though the example above is concerned with the project file XML you can also change these settings through the project properties UI in Visual Studio. As of Visual Studio 2022 these properties can be found at:
(RMB on project file) “Properties” -> “Build” -> “Errors and warnings” (section) -> “Treat warnings as errors” checkbox.
Enable TreatWarningsAsErrors or not?
Most developers would probably agree that treating warnings as errors is good practice. You should have zero warnings in your projects. However, on an existing project where warnings were not originally treated as errors it can be difficult to later enable because the project may have a large number of warnings that now need to be fixed all at once.
For this reason I would recommend enabling TreatWarningsAsErrors
for all new projects that way preventing warnings from accumulating. Instead they can be dealt with as they occur.
If you want to delve a little deeper Microsoft has a good article on C# Compiler Options to report errors and warnings.