- Projects and Tools
- Creating a Code Fix
- Building the Unit Tests for the if Diagnostic
- Finding Nodes
- Extending to the Other Cases
- Important Points to Remember
Building the Unit Tests for the if Diagnostic
Let's start building unit tests for the if diagnostic and code fix. There are six possible cases for an if / else statement and the presence of braces. To make it easier to see those cases, I created a console application in the sample repository with the following code (check out branch 02-SampleApplicationCode to experiment yourself):
if (b1) Console.WriteLine("b1"); if (b2) { Console.WriteLine("b1"); } if (b3) Console.WriteLine("b3"); else Console.WriteLine("not b3"); if (b4) { Console.WriteLine("b4"); } else Console.WriteLine("not b4"); if (b5) Console.WriteLine("b5"); else { Console.WriteLine("not b5"); } if (b6) { Console.WriteLine("b6"); } else { Console.WriteLine("not b6"); }
The Syntax Visualizer is invaluable at this stage of a project. Figure 2 shows the visualizer tree for the first and second if clauses. Notice that for the first example, the last child of the IfStatement is an ExpressionStatement. In the second example, the last child is a Block. Figure 3 shows the if statements with the if clauses added. Again, notice that the last child of the ElseClause could be either an ExpressionStatement or a Block.

Figure 2 The Roslyn Syntax Visualizer is an indispensable tool to view the syntax nodes created by code.

Figure 3 Using the Roslyn Syntax Visualizer, you can easily see the difference between clauses surrounded by braces and those without.
This simple example shows all the permutations for the structure of an if block. Regardless of the statements used, the child of the if statement will be either an ExpressionStatement or a Block. (The children of the ExpressionStatement or Block will represent the specific code written.
Now that we've looked at the example code, we know what the diagnostic analyzer needs to do: It will register to look at every if statement. It will examine the child of the if statement and report diagnostics when the child is an ExpressionStatement instead of a Block. It then will look for the presence of an else clause. When an else clause is present, it will report a diagnostic when the child of the else clause is an ExpressionStatement instead of a Block.
The corresponding CodeFixProvider will wrap the ExpressionStatement that triggered the diagnostic in a Block.