In C#, when is #pragma warning disable, [SuppressMessage] with a Justification, NoWarn or an .editorconfig severity of none the right way to silence a diagnostic?
answer
- scope: lines, symbol, folder, project
- pragma needs its restore
- attribute skips compiler warnings
- NoWarn hides future cases too
basics
~20 sPick the narrowest scope that fits: a #pragma warning disable and restore for a few lines, [SuppressMessage] with a Justification for one symbol's analyzer finding, .editorconfig none for a file pattern, and NoWarn for ids a whole project rejects.
solid answer
~40 s`#pragma warning disable CA2200` silences the listed ids from that line until `#pragma warning restore` or the end of the file, for compiler and analyzer ids alike; with no ids it silences every warning. `[SuppressMessage("Usage", "CA2200:...", Justification = "...")]` scopes the suppression to a symbol, or through `GlobalSuppressions.cs` with `Scope` and `Target`, and records why, but it silences analyzer diagnostics only: on the .NET 10 SDK it left the compiler's `CS0168` reported. An `.editorconfig` severity of `none` covers the files a section matches, which suits a tests folder. `NoWarn` removes the id from every file and every future occurrence of the project, and it beats `.editorconfig`. Trimming and AOT analysis read compiled IL, where `[SuppressMessage]` is not kept, so trim warnings need `[UnconditionalSuppressMessage]`.
code
csharp · 25 linesusing System;
using System.Diagnostics.CodeAnalysis;
public static class Calc
{
public static void Main()
{
#pragma warning disable CS0168 // placeholder kept for a later step
int a; // not reported
#pragma warning restore CS0168
int b; // CS0168 reported
Rethrow();
}
[SuppressMessage("Usage", "CA2200:Rethrow to preserve stack details",
Justification = "Legacy wrapper; callers log the inner exception")]
static void Rethrow()
{
try { Console.WriteLine(1); }
catch (Exception e) { throw e; } // CA2200 suppressed
}
[SuppressMessage("Compiler", "CS0168", Justification = "has no effect")]
static void Unused() { int c; } // CS0168 still reported
}go deeper
Know the pragma pair, disable with ids and restore, and that it covers lines, not files. Recall that [SuppressMessage] needs a category, a rule id and ideally a Justification.
Compare the four scopes: lines, symbol, file pattern, project. Explain why [SuppressMessage] does not touch compiler warnings and why NoWarn beats .editorconfig.
Show the production judgment: a bare pragma or project-wide NoWarn hides future findings, trim warnings need UnconditionalSuppressMessage, and accepted findings should carry a reason a reviewer can read.
Set the suppression rules for a team: which forms are allowed, that each needs a reason, who reviews changes to NoWarn and shared configuration, and how stale suppressions get revisited.
## Four tools, four scopes Every suppression trades a diagnostic the team has read for silence about every future case the same suppression covers, so the useful question is **scope**: how much code, and how much future code, does it hide? A second question is **visibility**: will the next reader of the code, or of the project file, see that something was silenced and why? The four tools answer both questions differently. | Tool | Scope | Covers compiler `CS` ids | Leaves a reason in code | |---|---|---|---| | `#pragma warning disable` / `restore` | the lines between the two directives | yes | only a comment you write | | `[SuppressMessage]` | one symbol, or a target named in `GlobalSuppressions.cs` | no | yes, `Justification` | | `.editorconfig` severity `none` | the files a section matches | yes | only a comment you write | | `NoWarn` property | the whole project, every build | yes | no | ## The pragma: a lexical region `#pragma warning disable CA2200` stops the compiler reporting the listed ids from that line onwards; `#pragma warning restore CA2200` ends the region, and without a restore it runs to the end of the file. It works on compiler and analyzer ids alike. Two traps: - **No ids means every warning.** A bare `#pragma warning disable` silences all warnings until the restore or the end of the file. On the .NET SDK 10.0.401, two unused locals after such a line were not reported. - **A forgotten restore** silently widens the region to the rest of the file, including code added years later. Use it for a few lines whose finding the team has read and accepted, with a comment saying why. ## The attribute: a symbol with a reason `[SuppressMessage(category, checkId, Justification = "...")]` from `System.Diagnostics.CodeAnalysis` suppresses one analyzer diagnostic on the symbol it decorates. Put at assembly level, usually in a `GlobalSuppressions.cs` file, it uses `Scope` (for example `"member"`) and `Target` (a documentation id such as `"~M:Calc.Rethrow"`) to point at the symbol. Its strengths: - the `Justification` string is visible in review and searchable later; - it survives reformatting and line moves, because it is attached to a symbol, not to lines. Its limits: - **Analyzer diagnostics only.** On the .NET SDK 10.0.401, `[SuppressMessage("Compiler", "CS0168", ...)]` on a method left `CS0168` reported, while the same attribute for `CA2200` silenced it. Compiler warnings need a pragma, `NoWarn` or a severity entry. - **Not in the assembly.** The attribute class carries `[Conditional("CODE_ANALYSIS")]`, so the compiler honours it from source but does not emit it into IL unless that symbol is defined. Trimming and Native AOT analysis run on compiled IL at publish and never see it; for warnings such as `IL2026`, the trimming guide asks for `[UnconditionalSuppressMessage]`, which is kept in the assembly. ## Configuration files: a folder or file pattern `dotnet_diagnostic.CA1822.severity = none` in an `.editorconfig` disables a rule for the files its section matches. A nested `.editorconfig` under a tests folder is the usual way to relax rules that make no sense for test code, and a conditional global AnalyzerConfig file does the same per project. The entry also accepts compiler ids, such as `dotnet_diagnostic.CS0168.severity = none`. ## NoWarn: the whole project, forever `<NoWarn>$(NoWarn);CS1591</NoWarn>` passes `-nowarn` to the compiler, so the id disappears from every file and every future occurrence in the project, and it wins over `.editorconfig`: on the .NET SDK 10.0.401 an id in `NoWarn` stayed silent even with `.editorconfig` asking for `error`. It is right for an id that makes no sense for a project at all, such as missing XML documentation comments in a test project; it is wrong as a way to get a stricter build green, because it also hides the next real finding. ## A working order of preference 1. Fix the code. 2. A pragma with ids, a restore and a comment, around the few lines concerned. 3. `[SuppressMessage]` with a `Justification` when the acceptance belongs to a symbol. 4. A severity entry for a folder, file pattern or project with a stated reason. 5. `NoWarn` only for ids the whole project rejects. Under `TreatWarningsAsErrors`, every one of these makes the diagnostic unreported, so none of them can fail the build, which is exactly why suppressions deserve the same review as code.
- Why does an [UnconditionalSuppressMessage] exist next to [SuppressMessage]?SuppressMessageAttribute is marked [Conditional("CODE_ANALYSIS")], so it is not emitted into the compiled assembly by default. Trimming and Native AOT analysis read IL at publish time, so they cannot see it. UnconditionalSuppressMessageAttribute is always emitted, which is why the trimming guide requires it for trim warnings such as IL2026.
- When is a GlobalSuppressions.cs entry better than an attribute on the member?When the target has no source to decorate, such as a compiler-generated constructor, or when a team wants all accepted findings in one reviewable file. The assembly-level attribute names the symbol with Scope and a documentation-id Target, for example ~M:Calc.Rethrow.
- What goes wrong with a bare #pragma warning disable?With no ids it disables every warning, compiler and analyzer, until a restore or the end of the file. New code added below it later is silenced too, so a review rule should require explicit ids and a matching restore.
- [SuppressMessage] can silence any diagnostic, compiler CS warnings included.
- A #pragma warning disable affects only the next line.
- NoWarn is a safe default for getting a warnings-as-errors build green.
- A [SuppressMessage] in source also suppresses trim warnings at publish.
- An .editorconfig error setting overrides an id listed in NoWarn.