Translate C# code into AST?

Erik Forbes picture Erik Forbes · Oct 17, 2008 · Viewed 11.3k times · Source

Is it currently possible to translate C# code into an Abstract Syntax Tree?

Edit: some clarification; I don't necessarily expect the compiler to generate the AST for me - a parser would be fine, although I'd like to use something "official." Lambda expressions are unfortunately not going to be sufficient given they don't allow me to use statement bodies, which is what I'm looking for.

Answer

Paul Rubel picture Paul Rubel · Oct 27, 2011

The Roslyn project is in Visual Studio 2010 and gives you programmatic access to the Syntax Tree, among other things.

SyntaxTree tree = SyntaxTree.ParseCompilationUnit(
    @" C# code here ");
var root = (CompilationUnitSyntax)tree.Root;