public async override Task RegisterCodeFixesAsync(CodeFixContext context) { var document = context.Document; var cancellationToken = context.CancellationToken; var span = context.Span; var diagnostics = context.Diagnostics; var root = await document.GetSyntaxRootAsync(cancellationToken); var semanticModel = await document.GetSemanticModelAsync(cancellationToken); var diagnostic = diagnostics.First(); var node = root.FindNode(context.Span) as IfStatementSyntax; var switchExpr = ConvertIfStatementToSwitchStatementCodeRefactoringProvider.GetSwitchExpression(semanticModel, node.Condition); if (switchExpr == null) { return; } var switchSections = new List <SwitchSectionSyntax>(); if (!ConvertIfStatementToSwitchStatementCodeRefactoringProvider.CollectSwitchSections(switchSections, semanticModel, node, switchExpr)) { return; } if (switchSections.Count(s => !s.Labels.OfType <DefaultSwitchLabelSyntax>().Any()) <= 2) { return; } var switchStatement = SyntaxFactory.SwitchStatement(switchExpr, new SyntaxList <SwitchSectionSyntax>().AddRange(switchSections)); var newRoot = root.ReplaceNode((SyntaxNode)node, switchStatement.WithAdditionalAnnotations(Formatter.Annotation)); context.RegisterCodeFix(CodeActionFactory.Create(node.Span, diagnostic.Severity, "Convert to 'switch' statement", document.WithSyntaxRoot(newRoot)), diagnostic); }
static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic) { var node = nodeContext.Node as IfStatementSyntax; var semanticModel = nodeContext.SemanticModel; var cancellationToken = nodeContext.CancellationToken; diagnostic = default(Diagnostic); if (nodeContext.IsFromGeneratedCode()) { return(false); } if (node.Parent is IfStatementSyntax || node.Parent is ElseClauseSyntax) { return(false); } var switchExpr = ConvertIfStatementToSwitchStatementCodeRefactoringProvider.GetSwitchExpression(semanticModel, node.Condition); if (switchExpr == null) { return(false); } var switchSections = new List <SwitchSectionSyntax>(); if (!ConvertIfStatementToSwitchStatementCodeRefactoringProvider.CollectSwitchSections(switchSections, semanticModel, node, switchExpr)) { return(false); } if (switchSections.Count(s => !s.Labels.OfType <DefaultSwitchLabelSyntax>().Any()) <= 2) { return(false); } diagnostic = Diagnostic.Create( descriptor, node.IfKeyword.GetLocation() ); return(true); }