Home
Map
Pragma DirectiveUse the #pragma directive to affect the compile-time reporting of warnings.
C#
This page was last reviewed on May 10, 2022.
Pragma directive. The #pragma directive disables the reporting of a warning. It is useful when you understand and expect the warning—but still want to disable it.
Warnings. With #pragma we can disable a specific warning or all warnings. Pragma can receive arguments like "warning disable" to change how the file is compiled.
Directives
Example. Remember that when the C# compiler detects unreachable code, it will report a warning. The compiler reports these errors to improve code quality—not to annoy the developer.
Here In this example, the if (false) statement results in unreachable code—the compiler will warn about this.
Unreachable
if
Tip By wrapping the #pragma warning disable directive and #pragma warning restore directive around the statement, we can hide the warning.
So When you compile this program, no warnings are reported by the C# compiler.
using System; class Program { static void Main() { // This example has unreachable code! // ... The pragma directives hide the warning. #pragma warning disable if (false) { Console.WriteLine("Perls"); } #pragma warning restore } }
You can optionally add another value after the directives. As the C# specification shows, you can use #pragma warning disable 612 to disable the C# compiler's warning number 612.
However This is probably more trouble than it is worth. It might be better to just disable all warnings in small blocks of code.
A discussion. These directives are useful in many programs. When developing, I sometimes will use the if (false) construction to comment out code but compile it anyways.
And This ensures that the code will not stop compiling and refactoring will update it.
Detail I can use the #pragma directives to indicate that I know the code is unreachable already and don't want to fix it.
A summary. The #pragma warning disable and restore directives influence how the compiler reports warnings. If you expect a certain warning, and don't want to fix it, #pragma directives are useful.
C#VB.NETPythonGolangJavaSwiftRust
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on May 10, 2022 (edit link).
Home
Changes
© 2007-2023 Sam Allen.