Search code examples
c#code-generationroslynroslyn-code-analysis

How to create a constructor with a parameter with Roslyn?


I'm generating classes from an Open API specification and need to create a constructor that accepts a parameter and sets it to a field. How do I do that with Roslyn?


Solution

  • I ended up using this code to create a constructor that accepts a parameter and sets it to a field:

    SyntaxFactory.ConstructorDeclaration("MyClass")
        .AddParameterListParameters(
            SyntaxFactory.Parameter(SyntaxFactory.Identifier("myParameter"))
                .WithType(SyntaxFactory.ParseTypeName("string")))
        .WithBody(SyntaxFactory.Block(SyntaxFactory.ParseStatement($"_myField = myParameter;")))
        .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword));
    

    The generated constructor for this code is:

    public MyClass(string myParameter)
    {
         _myField = myParameter;
    }