Skip to content

Pragma directives C# 2.0correctness

Use `#pragma warning` to selectively suppress or restore compiler warnings.

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 here
C#
int unusedButRequired; // Compiler warning CS0168 with no way to suppress locally

Notes

  • #pragma warning disable without a warning number suppresses all warnings for the following code - use this sparingly
  • #pragma warning restore re-enables warnings - always restore after disabling to limit the scope
  • Modern C# also supports #pragma warning disable with the newer CSXXXX format and analyzer rule IDs (e.g. CA1234)

More information