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
C#
#pragma warning disable 0168 // variable declared but never used
int unusedButRequired;
#pragma warning restore 0168
// Warnings are back in effect hereC#
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- Modern C# also supports
#pragma warning disablewith the newerCSXXXXformat and analyzer rule IDs (e.g.CA1234)