6

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

Andry
  • 16,172
  • 27
  • 138
  • 246
  • Possible duplicate: http://stackoverflow.com/questions/28234052/finding-all-class-declarations-than-inherit-from-another-with-roslyn – Tamir Vered Oct 04 '15 at 19:18
  • Actually my question is slightly different from that right? I mean, Yes in the end looks like the solution is the same, but here I am trying, more specifically, to distinguish between classes and interfaces. – Andry Oct 04 '15 at 20:07
  • Oh, I didn't understand your question properly, sorry mate! – Tamir Vered Oct 04 '15 at 20:08
  • Absolutely no problem, it is always good to analyze questions and report possible duplicates. Actually thanks to you I could find a question which is related to mine :) – Andry Oct 04 '15 at 20:09

1 Answers1

4

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.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964