예제 #1
0
        public static Task <Document> RefactorAsync(
            Document document,
            BlockSyntax block,
            CancellationToken cancellationToken)
        {
            SyntaxList <StatementSyntax> statements = block.Statements;

            var ifStatement = (IfStatementSyntax)statements[0];

            var returnStatement = (ReturnStatementSyntax)statements[1];

            var expressionStatement = (ExpressionStatementSyntax)ifStatement.GetSingleStatementOrDefault();

            var assignment = (AssignmentExpressionSyntax)expressionStatement.Expression;

            ExpressionSyntax expression = returnStatement.Expression.WithoutTrivia();

            BinaryExpressionSyntax coalesceExpression = CSharpFactory.CoalesceExpression(
                expression,
                CSharpFactory.SimpleAssignmentExpression(expression, assignment.Right.WithoutTrivia()).Parenthesize());

            ReturnStatementSyntax newReturnStatement = returnStatement
                                                       .WithExpression(coalesceExpression)
                                                       .WithLeadingTrivia(ifStatement.GetLeadingTrivia());

            SyntaxList <StatementSyntax> newStatements = statements
                                                         .Replace(returnStatement, newReturnStatement)
                                                         .RemoveAt(0);

            BlockSyntax newBlock = block.WithStatements(newStatements);

            return(document.ReplaceNodeAsync(block, newBlock, cancellationToken));
        }