1

I am trying to create a source generator for some automationg purpose. My target types are some classes which implement unknown interfaces. Those interfaces are decorated with a custom attribute. By searching everywhere, I can only find samples where people have attributes directly on target type, which unfortunately does not work in this case.

Here's that sample target code:

public sealed class SomeAttribute : Attribute
{

}

[Some]
public interface IA
{

}

internal sealed class A : IA
{

}

But in source generator ClassDeclarationSyntax does not seems to provide interfaces, instead I can only get attributes. This answer given here Roslyn CSharpSyntaxRewriter Get A List of Implemented Interfaces says that we can do following:

var root = classDeclarationSyntax.SyntaxTree.GetRoot();
var model = compilation.GetSemanticModel(root.SyntaxTree);
ISymbol? symbol = model.GetDeclaredSymbol(root.DescendantNodes().OfType<ClassDeclarationSyntax>().First())

var implementedInterfaces = symbol.AllInterfaces;

But this does not work for me as symbol does not contain AllInterfaces property. My question how can I get interface list from ClassDeclarationSyntax?

1 Answer 1

3

figured it out. We need to cast symbol to ITypeSymbol like below:

var interfaces = ((ITypeSymbol)symbol).AllInterfaces
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.