...

/

Treating Warning as Errors and Understanding Warning Waves

Treating Warning as Errors and Understanding Warning Waves

Learn about treating warnings as errors in C# to improve code quality, understand warning waves, and control which warnings to enable or disable.

Let’s see some ways to write better code in the C# language. 

Treating warnings as errors

A simple yet effective way to write better code is to force ourselves to fix compiler warnings. By default, warnings can be ignored. We can ask the compiler to prevent us from ignoring them.

Press + to interact

Let’s review the default experience and then see how we can improve it:

Step 1: Use your preferred code editor to add a Console App/console project named WarningsAsErrors to the Chapter06 solution or workspace.

Step 2: In Program.cs, modify the existing statements to prompt the user to enter a name and then say hello to them, as shown highlighted in the following code:

Press + to interact
Console.Write("Enter a name: ");
string name = Console.ReadLine();
Console.WriteLine($"Hello, {name} has {name.Length} characters!");

Step 3: Build the WarningsAsErrors project using dotnet build at the command line or terminal and note that the build succeeds, but there are two warnings, as shown in the following output:

Build succeeded.
/usercode/WarningsAsErrors/Program.cs(2,15): warning CS8600:
Converting null literal or possible null value to non-nullable
type. [/usercode/WarningsAsErrors/WarningsAsErrors.csproj]
/usercode/WarningsAsErrors/Program.cs(3,40): warning CS8602:
Dereference of a possibly null reference.
[/usercode/WarningsAsErrors/WarningsAsErrors.csproj]
2 Warning(s)
0 Error(s)

Step 4: Build the WarningsAsErrors project a second time using dotnet build at the command line or the terminal and note that the build succeeds, but the ...