Search code examples
c#sourcegenerators

How to access the syntax tree generated in another file in C# source generator?


I am writing a source generator in C#. First I get the class I need which I find by using an attribute. Then I need to find a class which is in another file. But I can't seem to find it.

My code is too long to put here but this is the way I am trying to do it :

services = classDeclarationSyntax.SyntaxTree.GetRoot().DescendantNodes()
                    .OfType<ClassDeclarationSyntax>()
                    .Where(n => n.Identifier.Text.Contains("Service")).ToList();

Obviously I am looking for classes that end with Service. If I put the classes in the same file it works fine but separating them breaks it. I think that it creates separate syntax trees for each file so getting the root node does not work.

Any idea on how to solve this?


Solution

  • You can use the Compilation.SyntaxTrees Property from the Compilation Class (the compilation context).