Reputation: 10015
I'm writing a simple Roslyn generator that generates an interface implementation so I want to get TypeSyntax
from TypeDeclarationSyntax
, because of following code:
// Our generator is applied to any class that our attribute is applied to.
var applyToInterface = (InterfaceDeclarationSyntax)applyTo;
// Trying to implement this interface
var clientClass = SyntaxFactory.ClassDeclaration(SyntaxFactory.Identifier(applyToInterface.Identifier.ValueText + "Client"))
.WithModifiers(SyntaxTokenList.Create(SyntaxFactory.Token(SyntaxKind.PublicKeyword)))
.WithBaseList(SyntaxFactory.SimpleBaseType(applyToInterface.???));
However, I don't see any way to create TypeSyntax except SyntaxFactory.ParseTypeName
. But I don't want to get interface name and then convert it back to type, because of possible bugs (like +
chars in generics instead of dot and so on).
What is the most convinient and recommended way to perform this operation? Currently I'm using
var clientClass = SyntaxFactory.ClassDeclaration(SyntaxFactory.Identifier(applyToInterface.Identifier.ValueText + "Client"))
.WithModifiers(SyntaxTokenList.Create(SyntaxFactory.Token(SyntaxKind.PublicKeyword)))
.AddBaseListTypes(SyntaxFactory.SimpleBaseType(SyntaxFactory.ParseTypeName(applyToInterface.Identifier.ValueText)));
But i'm not sure if it's correct always.
Upvotes: 3
Views: 1490
Reputation: 21005
I believe the way you are doing it is correct, Due to Roslyn's lack of documentation I generally check their source to use internal examples to check my samples. I've found this sample from searching WithBaseList
var implementedInterfaceTypeSyntax = extractedInterfaceSymbol.TypeParameters.Any()
? SyntaxFactory.GenericName(
SyntaxFactory.Identifier(extractedInterfaceSymbol.Name),
SyntaxFactory.TypeArgumentList(SyntaxFactory.SeparatedList(extractedInterfaceSymbol.TypeParameters.Select(p => SyntaxFactory.ParseTypeName(p.Name)))))
: SyntaxFactory.ParseTypeName(extractedInterfaceSymbol.Name);
var baseList = typeDeclaration.BaseList ?? SyntaxFactory.BaseList();
var updatedBaseList = baseList.WithTypes(SyntaxFactory.SeparatedList(baseList.Types.Union(new[] { SyntaxFactory.SimpleBaseType(implementedInterfaceTypeSyntax) })));
In this instance they are using the symbol to generate the type.
Upvotes: 3