Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Howto create a const declaration using .NET Compiler Platform

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

like image 922
Sabrina_cs Avatar asked Jun 02 '16 19:06

Sabrina_cs


1 Answers

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)}))))))
like image 163
JoshVarty Avatar answered Oct 19 '22 00:10

JoshVarty