private static void AddBracesToIfElseChain(CodeRefactoringContext context, IfStatementSyntax ifStatement)
        {
            if (IfElseChainAnalysis.IsTopmostIf(ifStatement) &&
                ifStatement.Else != null &&
                ifStatement.IfKeyword.Span.Contains(context.Span))
            {
                var result = new IfElseChainAnalysisResult(ifStatement);

                if (result.AddBracesToChain)
                {
                    context.RegisterRefactoring(
                        "Add braces to if-else chain",
                        cancellationToken =>
                    {
                        return(AddBracesToIfElseChainRefactoring.RefactorAsync(
                                   context.Document,
                                   ifStatement,
                                   cancellationToken));
                    });
                }

                if (result.RemoveBracesFromChain)
                {
                    context.RegisterRefactoring(
                        "Remove braces from if-else chain",
                        cancellationToken =>
                    {
                        return(RemoveBracesFromIfElseChainRefactoring.RefactorAsync(
                                   context.Document,
                                   ifStatement,
                                   cancellationToken));
                    });
                }
            }
        }
Exemplo n.º 2
0
        public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            SyntaxNode root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);

            IfStatementSyntax ifStatement = root
                                            .FindNode(context.Span, getInnermostNodeForTie: true)?
                                            .FirstAncestorOrSelf <IfStatementSyntax>();

            if (ifStatement == null)
            {
                return;
            }

            ifStatement = IfElseChainAnalysis.GetTopmostIf(ifStatement);

            CodeAction codeAction = CodeAction.Create(
                "Add braces to if-else chain",
                cancellationToken => AddBracesToIfElseChainRefactoring.RefactorAsync(context.Document, ifStatement, cancellationToken),
                DiagnosticIdentifiers.AddBracesToIfElseChain + EquivalenceKeySuffix);

            context.RegisterCodeFix(codeAction, context.Diagnostics);
        }