I'm trying to create a small code generator using Roslyn or as it is called now .NET Compiler Platform, prevously I worked with codedom, which was cumbersome but MSDN got a reference, now Roslyn has little documentation and all documentation is focused on code analysis instead of code generation. So my question is simple: How can I create something like:
private const string MyString = "This is my string";
using the Compiler Platform classes? I've found something like FieldDeclarationSyntax and ExpressionSyntax, but all samples I've found generate things like Myclass myvariable = new Myclass(); And there is nothing telling me something so simple as how to produce the string type declaration. any clue will be great. Thank you in advance
You can use Roslyn Quoter to easily figure out how to build different pieces of syntax. In this case you're wanting to add the const
and private
modifiers to a field declaration so it would look something like:
var constField = SyntaxFactory.FieldDeclaration(
SyntaxFactory.VariableDeclaration(
SyntaxFactory.PredefinedType(
SyntaxFactory.Token(SyntaxKind.StringKeyword)))
.WithVariables(
SyntaxFactory.SingletonSeparatedList<VariableDeclaratorSyntax>(
SyntaxFactory.VariableDeclarator(
SyntaxFactory.Identifier("MyString"))
.WithInitializer(
SyntaxFactory.EqualsValueClause(
SyntaxFactory.LiteralExpression(
SyntaxKind.StringLiteralExpression,
SyntaxFactory.Literal("This is my string")))))))
.WithModifiers(
SyntaxFactory.TokenList(
new []{
SyntaxFactory.Token(SyntaxKind.PrivateKeyword),
SyntaxFactory.Token(SyntaxKind.ConstKeyword)}))))))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With