public static async Task ComputeRefactoringsAsync(RefactoringContext context, CastExpressionSyntax castExpression) { if (context.IsRefactoringEnabled(RefactoringIdentifiers.ReplaceCastWithAs) && context.Span.IsEmptyAndContainedInSpanOrBetweenSpans(castExpression)) { SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(castExpression.Type, context.CancellationToken); if (typeSymbol?.IsErrorType() == false && typeSymbol.IsReferenceTypeOrNullableType()) { Document document = context.Document; context.RegisterRefactoring( "Replace cast with 'as'", cancellationToken => { BinaryExpressionSyntax newNode = CSharpFactory.AsExpression(castExpression.Expression.WithTriviaFrom(castExpression.Type), castExpression.Type.WithTriviaFrom(castExpression.Expression)) .WithTriviaFrom(castExpression) .WithFormatterAnnotation(); return(document.ReplaceNodeAsync(castExpression, newNode, cancellationToken)); }, RefactoringIdentifiers.ReplaceCastWithAs); } } }
private static Task <Document> RefactorAsync( Document document, CastExpressionSyntax castExpression, CancellationToken cancellationToken) { ExpressionSyntax expression = castExpression.Expression; TypeSyntax type = castExpression.Type; BinaryExpressionSyntax newNode = CSharpFactory.AsExpression(expression.WithTriviaFrom(type), type.WithTriviaFrom(expression)) .WithTriviaFrom(castExpression) .WithFormatterAnnotation(); return(document.ReplaceNodeAsync(castExpression, newNode, cancellationToken)); }