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(), ""));
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With