Translate C# code into AST?

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;

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

Yes, trivially in special circumstances (= using the new Expressions framework):

// Requires 'using System.Linq.Expressions;'
Expression<Func<int, int>> f = x => x * 2;

This creates an expression tree for the lambda, i.e. a function taking an int and returning the double. You can modify the expression tree by using the Expressions framework (= the classes from in that namespace) and then compile it at run-time:

var newBody = Expression.Add(f.Body, Expression.Constant(1));
f = Expression.Lambda<Func<int, int>>(newBody, f.Parameters);
var compiled = f.Compile();
Console.WriteLine(compiled(5)); // Result: 11

Notice that all expressions are immutable so they have to be built anew by composition. In this case, I've prepended an addition of 1.

Notice that these expression trees only work on real expressions i.e. content found in a C# function. You can't get syntax trees for higher constructs such as classes this way. Use the CodeDom framework for these.


Check out .NET CodeDom support. There is an old article on code project for a C# CodeDOM parser, but it won't support the new language features.

There is also supposed to be support in #develop for generating a CodeDom tree from C# source code according to this posting.