using Microsoft.CodeAnalysis.CSharp.SyntaxFactory; // Create a new instance of a class with a constructor var classDeclaration = SyntaxFactory.ClassDeclaration("MyClass") .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword)) .AddMembers( SyntaxFactory.ConstructorDeclaration("MyClass") .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword)) .WithBody(SyntaxFactory.Block())); // Output the generated code Console.WriteLine(classDeclaration.ToFullString());
using Microsoft.CodeAnalysis.CSharp.SyntaxFactory; // Create a new method declaration with arguments var methodDeclaration = SyntaxFactory.MethodDeclaration( SyntaxFactory.PredefinedType( SyntaxFactory.Token(SyntaxKind.VoidKeyword)), "MyMethod") .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword)) .AddParameterListParameters( SyntaxFactory.Parameter( SyntaxFactory.Identifier("arg1")) .WithType( SyntaxFactory.PredefinedType( SyntaxFactory.Token(SyntaxKind.IntKeyword))), SyntaxFactory.Parameter( SyntaxFactory.Identifier("arg2")) .WithType( SyntaxFactory.PredefinedType( SyntaxFactory.Token(SyntaxKind.StringKeyword)))) .WithBody( SyntaxFactory.Block( SyntaxFactory.ReturnStatement())); // Output the generated code Console.WriteLine(methodDeclaration.ToFullString());In this example, we use SyntaxFactory to create a new method declaration with two arguments. We specify the return type as void, and add public access modifier to the method. We then add the arguments using the AddParameterListParameters method, and use WithBody method to add a block containing a return statement. We then output the generated code using the ToFullString method. Package library: Microsoft.CodeAnalysis.CSharp.SyntaxFactory