Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding new field declaration to class with Roslyn

There is some way to add a member to a class with roslyn? I want to add :

public int number {get;set;}

UPDATE I used this code:

       PropertyDeclarationSyntax o =  
       SyntaxFactory.PropertyDeclaration(SyntaxFactory.ParseTypeName("public  
       System.Windows.Forms.Timer"), "Ticker { get; set; }");

       var newRoot = root.ReplaceNode(oldMethod, oldMethod.AddMembers(o));
       newRoot = Formatter.Format(newRoot, new AdhocWorkspace());

       File.WriteAllText(file, newRoot.ToFullString());

But the the result is this:

   public class ClassChild
{
    public int n;
    private int n2;

    public void method1()
    {
        string c = "";
        Console.WriteLine();
    }

public System.Windows.Forms.TimerTicker { get; set; }
}

}

I would like to inline public System.Windows.Forms.TimerTicker { get; set; } with n and n2. How Can I do this ?

like image 819
blinkettaro Avatar asked Jul 18 '17 07:07

blinkettaro


1 Answers

See the code

    private PropertyDeclarationSyntax MakeProperty()
    {
        string name = "n";

        // Create an auto-property
        var property =
            SyntaxFactory.PropertyDeclaration(SyntaxFactory.ParseTypeName("int"), name)
            .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword))
            .AddAccessorListAccessors(
                SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)),
                SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken))
            );

        return property;
    }

    private async Task<Document> AddProperty(Document document, ClassDeclarationSyntax classeDecl, CancellationToken cancellationToken)
    {
        var root = await document.GetSyntaxRootAsync(cancellationToken);
        var newClass = classeDecl.AddMembers(MakeProperty());
        return document.WithSyntaxRoot(root.ReplaceNode(classeDecl, newClass));
    }

Auto property genaration example is taken from this question.

like image 135
Oxoron Avatar answered Sep 19 '22 18:09

Oxoron