13

I want to do some very basic code-gen (converting a service API spec to some C# classes for communicating with the service). I found this question that seems to suggest I can call Syntax.CompilationUnit() to create a new CompilationUnityntax, however I'm unable to make this code compile; I can't find a CompilationUnit method on any of the Syntax classes I can find (nor can I locate any docs on this) :(

CSharpSyntaxTree.Create appears to need a CSharpSyntaxNode, but I can't figure out how to create one of them either :/

I'm using VS 2015 RC with the latest Microsoft.CodeAnalysis NuGet package (1.0.0-rc2).

Community
  • 1
  • 1
Danny Tuppeny
  • 40,147
  • 24
  • 151
  • 275
  • 1
    Your question inspired me to give a short overview of the (new?) roslyn API. Check it out here: http://www.vannevel.net/2015/06/07/a-few-important-roslyn-api-helpers/ – Jeroen Vannevel Jun 07 '15 at 21:30
  • @JeroenVannevel sadly, your link is dead :o( – mike Feb 20 '22 at 22:34
  • @mike: I can't edit my previous comment but you can find that post here: https://vannevel.net/posts/a-few-important-roslyn-api-helpers/ – Jeroen Vannevel Feb 21 '22 at 15:01

1 Answers1

12

Seems that Syntax is now SyntaxFactory:

var comp = SyntaxFactory.CompilationUnit()
        .AddMembers(
            SyntaxFactory.NamespaceDeclaration(SyntaxFactory.IdentifierName("ACO"))
                    .AddMembers(
                    SyntaxFactory.ClassDeclaration("MainForm")
                        .AddMembers(
                            SyntaxFactory.PropertyDeclaration(SyntaxFactory.ParseTypeName("System.Windows.Forms.Timer"), "Ticker")
                                    .AddAccessorListAccessors(
                                    SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)),
                                    SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken))),
                            SyntaxFactory.MethodDeclaration(SyntaxFactory.ParseTypeName("void"), "Main")
                                    .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword))
                                    .WithBody(SyntaxFactory.Block())
                            )
                    )
            );
Danny Tuppeny
  • 40,147
  • 24
  • 151
  • 275
  • Yes. I noticed many of the examples use static using statements to include SyntaxFactory. Such as `using static Microsoft.CodeAnalysis.SyntaxFactory;` which allows all members to be called without specifying the static type name. – SimperT Apr 17 '18 at 01:27
  • `using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;` – mike Feb 20 '22 at 22:49