2

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?

1 Answer 1

1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.