Matthias
Matthias

Reputation: 16209

How to create generic type reference with Roslyn?

I want to create a reference to "System.IEquatable<MyType>", where the open generic type can be reached via typeof and the generic argument as text only. How do I create a correct NameSyntax that can be used as field type, etc.?

We recently used SF.ParseName which creates a QualifiedNameSyntax (not a GenericNameSyntax what wonders me). However, I think this is not ideal, since I'm dealing with <, > and string.Join on my own.

Upvotes: 2

Views: 1409

Answers (2)

Srivatsn Narayanan
Srivatsn Narayanan

Reputation: 404

If you are doing this in the workspace layer, you can also use the SyntaxGenerator type to do this in a language independent way:

var generator = SyntaxGenerator.GetGenerator(document);
generator.QualifiedName(generator.IdentifierName("System"),
                        generator.GenericName(generator.IdentifierName("IEquatable"), 
                                              new [] { generator.IdentifierName("MyType") }));

This will generate System.IEquatable< MyType> for C# and System.IEquatable(Of MyType) for VB documents.

Upvotes: 3

Jb Evain
Jb Evain

Reputation: 17499

You can use the following pattern:

SF.GenericName(
    SF.Identifier(@"IEquatable"))
.WithTypeArgumentList(
    SF.TypeArgumentList(/.../))

Upvotes: 1

Related Questions