Rosyln API Recipies Part 001

This blog post focuses on featuring couple of reusuable methods which one could find useful when working on Code Analyzer/CodeFix or Source Generators.

HasAttribute

Quite often one needs to check if the member declaration like Class, Property, Enum declaration has a particular attribute. The following method helps in detecting the same.

public static bool HasAttribute<TAttribute>(this MemberDeclarationSyntax source) where TAttribute : Attribute
{
    var attributeName = typeof(TAttribute).Name.Replace("Attribute", string.Empty);
    var attributes = source.AttributeLists;
    return attributes.Any(x => x.Attributes.Any(c => c.Name.GetText().ToString() == attributeName));
}

We use the MemberDeclarationSyntax.AttributeLists property to iterate over the attributes applied over the Member to detect if the required attribute is applied.

IsAsync

In order to check if the method is an asynchronous method, we scan through the Modifiers collection of MethodDeclarationSyntax.Modifiers to check if the AsyncKeyword is applied.

public static bool IsAsync(this MethodDeclarationSyntax source)
{
    return source.Modifiers.Any(SyntaxKind.AsyncKeyword); ;
}

RenameMethod

In order to rename a method, you could use the Microsoft.CodeAnalysis.Rename.Renamer.RenameSymbolAsync utility to rename the method.

public static async Task<Solution> RenameMethod(this MethodDeclarationSyntax methodDeclaration,Document document, string newName, CancellationToken cancellationToken)
{
    var solution = document.Project.Solution;

    var semanticModel = await document.GetSemanticModelAsync(cancellationToken);
    if (semanticModel == null) return default;

    var symbol = semanticModel.GetDeclaredSymbol(methodDeclaration, cancellationToken);

    var newSolution = await Renamer.RenameSymbolAsync(solution, symbol, newName, solution.Workspace.Options);
    return newSolution;
}


We will continue the recipe series for Roslyn API in future posts as well, but it is quite useful to document such utility methods so that it could be beneficial for other developers.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s