Search code examples
.netroslynsourcegenerators

.NET 6 Source Generator => TypeDeclarationSyntax get Members of Base Type


we are generating classes from interfaces using source generators. This works fine for non-extended interfaces.

However, we also have interfaces which inherit from another interface and we want to create a class containing properties from both interfaces.

Example:

public interface Core {
    int Id { get; set; }
}


public interface Extended : Core {
    string Description { get; set; }
}

What we want to produce using Roslyn Source Generators:

public class Impl {
    public int Id { get; set; }
    public string Description { get; set; }
}

We can access the interface Members using typeDeclarationSyntax.Members. Is it possible to get the members for the base type when processing the typeDeclarationSyntax for the Extended type? E.g. typeDeclarationSyntax.BaseInterface.Members.

Solution

According to the great answer from @Jason Malinowski, I want to share the code I used to get the semantic model.

var semanticModel = compilation.GetSemanticModel(typeDeclarationSyntax.SyntaxTree);
var declaredSymbol = semanticModel.GetDeclaredSymbol(typeDeclarationSyntax);

Solution

  • For things like that, you want to switch over from using syntax to the symbol model and semantics. Once you have the TypeDeclarationSyntax, call SemanticModel.GetDeclaredSymbol, that will give you an ITypeSymbol you can then use to walk the base hierarchy, get members, etc.