what correct way check variable's type in roslyn code analyzer? registering objectcreationexpressionsyntax node , can type, not correct way check type care about.
i found way checking display string, wondering if there more correct way accomplish this. example, here code trying check arraylist creation.
private static void syntaxvalidator(syntaxnodeanalysiscontext context) { var creation = (objectcreationexpressionsyntax)context.node; var variabletype = creation.type 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 doing use compilation.gettypebymetadataname(), , compare itypesymbol 1 got semanticmodel.gettypeinfo().
note: make sure use .equals compare itypesymbol instances, of them not guarantee reference identity.
see: http://source.roslyn.io/roslyn.diagnostics.analyzers/r/fee46febeb0be269.html example of analyzer this.
Comments
Post a Comment