Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell classes from interfaces in Roslyn's `BaseList`?

I am using Roslyn to analyze C# code. One of the things I need to have is analyzing a class declaration node and get information about:

  • Its base class
  • Its implemented interfaces

I can get access to the class declaration node (type ClassDeclarationSyntax), and from there I can get access to the BaseList:

ClassDeclarationSyntax node = ...; // The class declaration
BaseListSyntax baseList = node.BaseList;

However baseList contains both interfaces and classes. I need ti distinguish classes from interfaces. How?

Do I need to use the SemanticModel?

I've searched Roslyn's Wiki and discovered that it is possible to access semantic information from my AST.

SyntaxTree programRoot = ...; // Getting the AST root
CSharpCompilation compilation = CSharpCompilation.Create("Program")
    .AddReferences(MetadataReference.CreateFromFile(
    typeof(object).Assembly.Location))
    .AddSyntaxTrees(programRoot);

But how to get those info from here? Thanks

like image 508
Andry Avatar asked Sep 26 '22 14:09

Andry


1 Answers

Yes.

The syntax tree just knows what words are where; it doesn't know anything about what an identifier refers to.

You need to get the SemanticModel from the compilation), then call GetSymbolInfo() on each identifier node in the list. You can then cast the symbol to ITypeSymbol to find out about the type.

like image 186
SLaks Avatar answered Sep 30 '22 05:09

SLaks