Roslyn Annotations for Code Fix

 
 
  • Gérald Barré

Roslyn analyzers detect patterns in your code and report them as diagnostics. They can also provide code fixes that transform the existing SyntaxTree into a corrected one.

Roslyn provides the concept of annotations to mark nodes in the syntax tree. You can use special annotations to instruct Roslyn to post-process the syntax tree returned by a code fix and perform specific actions. This post describes the most common annotations.

Simplifier.Annotation removes unnecessary elements from your code. For instance, it can remove unnecessary parentheses or simplify type names. This is useful when generating an expression that is valid and has the correct evaluation order, while still allowing the simplifier to remove parentheses when possible.

C#
// Souround the expression with parentheses. If the compiler determines that the parentheses are not needed, it will remove them.
public static ParenthesizedExpressionSyntax Parentheses<T>(this ExpressionSyntax expression)
{
    return SyntaxFactory.ParenthesizedExpression(expression)
        .WithAdditionalAnnotations(Simplifier.Annotation);
}

Simplifier.AddImportsAnnotation adds missing using directives to your code.

C#
generator.TypeExpression(cultureInfo)
    .WithAdditionalAnnotations(Simplifier.AddImportsAnnotation);

Formatter.Annotation formats the code based on the configuration (EditorConfig). It will remove unnecessary whitespaces, add missing whitespaces, etc. Be careful to add it only to the node that you actually edited. Otherwise, you may reformat the whole file which is not acceptable from a user perspective.

C#
newNode.WithAdditionalAnnotations(Formatter.Annotation);

RenameAnnotation.Create() is used to rename a symbol. After applying the code fix, the IDE prompts the user to provide a name for the symbol. For example, you can use this annotation when introducing a new member and you want to let the user choose its name.

C#
Identifier(methodName).WithAdditionalAnnotations(RenameAnnotation.Create());

You can find other annotations in the Microsoft.CodeAnalysis namespace such as ElasticAnnotation, ConflictAnnotation, WarningAnnotation, etc., but they are less common.

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?