Adding new field declaration to class with Roslyn

Viewed 1883

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 ?

2 Answers

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();
Related