Suppressing C# Compiler Warnings

The C# compiler can generate warnings to indicate possible problems with source code that do not prevent compilation. In some circumstances warnings are expected and may be ignored. In such situations, individual types of warning can be suppressed.

Compiler Warnings

When you compile C# source code, the compiler may produce errors and warnings. An error indicates a serious problem with the code and causes the build process to fail. A warning is less serious and only causes a build failure if warnings are being treated as errors. In most situations, warnings are displayed within Visual Studio or your preferred alternative integrated development environment (IDE). In Visual Studio, warnings are displayed in the Error List and the Output pane, and are highlighted in the code editor with a green wavy underline.

To demonstrate some compiler warnings, try building the following code:

class Test
{
int unused;
int assigned = 3;
}

Two warnings are generated for the above code. One indicates that the unused variable is never used. The second states that the assigned variable has a value assigned but is never used again. Both of these conditions may indicate a problem with the source code. The warnings should be similar to those shown below:

warning CS0169: The field 'Test.unused' is never used
warning CS0414: The field 'Test.assigned' is assigned but its value is never used

Suppressing Warnings

Sometimes warnings generated during a build are expected. You may prefer to hide such warnings so that other problems are easier to spot. This can be achieved using the pragma warning compiler directive. To disable warnings, a comma-separated list of warning numbers is provided to the directive along with the disable keyword. The list should contain the integer part of the warning numbers only. All warnings of the specified types are ignored from the position of the directive until the end of the file.

To disable the two warnings mentioned above, which have the codes CS0169 and CS0414, use the directive shown below. Try compiling the code again to see that the warnings are no longer reported.

Re-Enabling Warnings

You should suppress compiler warnings for the smallest number of lines of code possible to avoid the risk that unexpected warnings will be hidden. To re-enable warnings, the restore keyword is used, as shown below: