Roslyn code generation, how to create a type expression for a given type

Viewed 238

I'm trying to generate code using Roslyn. I create a method like this:

var workspace = new AdhocWorkspace();
var generator = SyntaxGenerator.GetGenerator(workspace, LanguageNames.CSharp);

var parameters = new SyntaxNode[] { generator.ParameterDeclaration("MyParam", generator.TypeExpression(SpecialType.System_Boolean))};

var body = ...

var method = generatpr.MethodDeclaration(
   "MyMethod", 
   parameters,
   null, 
   null,
   Accessibility.Public,
   DeclarationModifiers.Virtual,
   new SyntaxNode[] { body});

My question is, how do I create parameters of other types like Guid, or other structs or classes? And can I do it in a way that is language agnostic?

1 Answers

yntaxGenerator instance, and I have an instance of a Type object, so I used the SyntaxGenerator.IdentifierName() function, and passed in the FullName property of the Type instance.

var workspace = new AdhocWorkspace();
var generator = SyntaxGenerator.GetGenerator(workspace, LanguageNames.CSharp);

var parameters = new SyntaxNode[] { generator.ParameterDeclaration("MyParam", generator.IdentifierName(typeParameter.FullName))};

var body = ...

var method = generatpr.MethodDeclaration(
   "MyMethod", 
   parameters,
   null, 
   null,
   Accessibility.Public,
   DeclarationModifiers.Virtual,
   new SyntaxNode[] { body});
Related