private void AnalyzeIfOrElseStatement(SyntaxNodeAnalysisContext context) { if (context.IsGeneratedOrNonUserCode()) { return; } IfStatementSyntax ifStatement = context.Node as IfStatementSyntax; // Is this an if statement followed directly by a call with no braces? if ((ifStatement != null) && (ifStatement.Statement != null) && (ifStatement.Statement.IsKind(SyntaxKind.Block) == false)) { Location loc = ifStatement.GetLocation(); Diagnostic diagnostic = Diagnostic.Create(Rule, loc, "if"); context.ReportDiagnostic(diagnostic); } // Is this an else clause followed by a call with no braces? ElseClauseSyntax elseSyntax = context.Node as ElseClauseSyntax; if ((elseSyntax != null) && (elseSyntax.Statement != null) && (elseSyntax.Statement.IsKind(SyntaxKind.IfStatement) == false) && (elseSyntax.Statement.IsKind(SyntaxKind.Block) == false)) { Location loc = elseSyntax.GetLocation(); Diagnostic diagnostic = Diagnostic.Create(Rule, loc, "else"); context.ReportDiagnostic(diagnostic); } }
public static void Analyze(SyntaxNodeAnalysisContext context, ElseClauseSyntax elseClause) { StatementSyntax statement = elseClause.Statement; if (statement?.IsKind(SyntaxKind.Block) == true) { var block = (BlockSyntax)statement; if (!block.Statements.Any() && elseClause .DescendantTrivia(elseClause.Span) .All(f => f.IsWhitespaceOrEndOfLineTrivia())) { context.ReportDiagnostic(DiagnosticDescriptors.RemoveEmptyElseClause, elseClause.GetLocation()); } } }