blinkettaro
blinkettaro

Reputation: 361

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 ?

Upvotes: 6

Views: 2630

Answers (2)

Y.H.Cohen
Y.H.Cohen

Reputation: 43

Personally, I prefer this kind of technique:

public static class SyntaxHelpers
{
    public static T GenerateClassNode<T>(string decl) where T : CSharpSyntaxNode
    {
        var declaration = SyntaxFactory.ParseCompilationUnit(
            " public class FSM { \r\n" +
            $"{decl}\r\n" +
            " }} \r\n");

        var field = declaration.Members[0].DescendantNodes().First() as T;
        return field;
    }
}

Then you can use it as following:

string log4NetLoggerDeclaration =
                    "private static readonly log4net.ILog Logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);";

var log4NetDeclarationStatement = SyntaxHelpers.GenerateClassNode<FieldDeclarationSyntax>(log4NetLoggerDeclaration);

string declarationString = log4NetLoggerDeclaration.ToString();

Upvotes: 0

Oxoron
Oxoron

Reputation: 674

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.

Upvotes: 6

Related Questions