I'm writing a source generator in C#, and I've got 2 objects that I need to compare to see if they relate to the same class, but I can't find a way to do it.
My first object is an instance of ClassDeclarationSyntax
. This is coming from my custom ISyntaxContextReceiver
to find classes that match specific conditions.
Elsewhere in my generator I have an IdentifierNameSyntax
object, which is coming from looking at the types within a TypeOfExpressionSyntax
that I find within a different class's list of attributes.
I need to compare the two objects here to see if they are talking about the same thing.
With the IdentifierNameSyntax
I can get the type information by using the semantic model:
ITypeSymbol semanticType = semanticModel.GetTypeInfo(targetType).Type;
But I don't know how to compare this ITypeSymbol
against ClassDeclarationSyntax
either.
Is there a way to do this, or is there a way to get the semantic model type information for a ClassDeclarationSyntax
object?
The method you are looking for is GetDeclaredSymbol
on semanticModel
. As you can see from the documentation, there are huge number of overloads which will allow you to get the associated symbol information for not only classes, but also fields, methods, properties, events, parameters, and so forth. Definitely a method you'll want to keep in your back pocket!