Compiler warnings are useful for catching potential problems but sometimes a warning is intentional or unavoidable. In C# 1.0 the only options were to disable the warning for the entire project via compiler switches or to live with the noise.
C# 2.0 adds #pragma warning directives to suppress and restore specific warnings at the source level, keeping the rest of the codebase protected.
Code
csharp
#pragma warning disable 0168 // variable declared but never used
int unusedButRequired;
#pragma warning restore 0168
// Warnings are back in effect herecsharp
int unusedButRequired; // Compiler warning CS0168 with no way to suppress locallyNotes
#pragma warning disablewithout a warning number suppresses all warnings for the following code - use this sparingly#pragma warning restorere-enables warnings - always restore after disabling to limit the scope- Current compilers also accept the
CSprefix (e.g.CS0168) and analyzer rule IDs (e.g.CA1234) - C# 2.0 also added
#pragma checksum, used by tools such as ASP.NET to help the debugger match generated code to its source file - See Experimental attribute C# 12.0 for the attribute that produces a warning suppressed with the same directive.