Home > Articles > Programming > C#

  • Print
  • + Share This
From the author of Extending to the Other Cases

Extending to the Other Cases

Once we've finished this first case, we're actually close to finishing the code. One of the great things about the Diagnostic and CodeFix APIs is that they are very consistent; once you have some basic concepts, you can apply those concepts—and the code—almost anywhere. That's true as we finish up the if clause diagnostic. The next case passes without any additional code:

if (b2)

The third case introduces the ElseClause, and we do need to add code for that (check out branch 07-ElseClauseTest). The code for AnalyzeIfBlock now needs to check for the presence of an Else clause. When an Else clause exists, the same check happens: Determine whether the statement that's part of the ElseClause is an ExpressionStatement or a Block. When it's an ExpressionStatement, create a new diagnostic and report it:

// check the else clause:
var elseStatement = statement.Else;
if (elseStatement != null)
    if (elseStatement.Statement is ExpressionStatementSyntax)
        var location = elseStatement.Statement.GetLocation();
        var diagnostic = Diagnostic.Create(Rule, location, "false (else) clause");

Once this code is added to the diagnostic, this test is very close to passing (check out branch 08-CodeFixTheElseClauses). This case now produces two diagnostics instead of one. That's perfectly valid for a diagnostic. Again, the only mistake is a bit of formatting involving the trivia. The CodeFixProvider needs to add the closing EndOfLineTrivia:

var block = SyntaxFactory.Block(openingTokenWithTrivia, statements, closingTokenWithTrivia)

That addition will format the output correctly, and now all the tests will pass (check out branch 09-FixTriviaForElse). The tests for the other cases can all be added now as well. They'll all pass with the code we've already created. To see the finished version, check out the master branch.

  • + Share This
  • 🔖 Save To Your Account