Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking a Variable Type For Code Analysis

What is the correct way to check a variable's type in a Roslyn code analyzer? I am registering for a ObjectCreationExpressionSyntax node and I can get the type, but I am not certain the correct way to check that it is a type I care about.

I found a way to do it by checking the display string, but I am wondering if there is a more correct way to accomplish this. For example, here is code that is trying to check for an ArrayList creation.

private static void SyntaxValidator(SyntaxNodeAnalysisContext context)
{
    var creation = (ObjectCreationExpressionSyntax)context.Node;

    var variableType = creation.Type as IdentifierNameSyntax;

    if (variableType == null)
        return;

    var variableTypeInfo = context.SemanticModel.GetTypeInfo(context.Node);

    if (variableTypeInfo.Type != null && variableTypeInfo.Type.ToDisplayString().Equals("System.Collections.ArrayList"))
    {
        context.ReportDiagnostic(Diagnostic.Create(Rule, creations.GetLocation(), ""));
    }
} 
like image 512
John Koerner Avatar asked Jul 11 '15 14:07

John Koerner


1 Answers

The normal pattern for doing this is to use Compilation.GetTypeByMetadataName(), and then compare that ITypeSymbol with The one you got back from SemanticModel.GetTypeInfo().

Note: Make sure to use .Equals to compare ITypeSymbol instances, as some of them do not guarantee reference identity.

See: http://sourceroslyn.io/Roslyn.Diagnostics.Analyzers/R/fee46febeb0be269.html for an example of an analyzer that does this.

like image 92
Kevin Pilch Avatar answered Sep 30 '22 07:09

Kevin Pilch