tags:

views:

367

answers:

5

What I want to do is to read C# code, parse it, insert some method calls and compile it finally.

Now. Is it possible to convert C# source code (a list of strings) to CodeDOM objects?

+2  A: 

Try Linq over C#. It's wonderful.

Tamás Szelei
A: 

The CSharpCodeProvider might be what you're looking for.

luiscubal
NO. I don't think CSharpCodeProvider can do what I described above.
ulrichb
A: 

Try Mono.Cecil

Pawel Lesnikowski
But it does not deal with source code. Or does it?
Tamás Szelei
Correct, it deals with IL only. You could use NRefactory (which is a parser for C# and VB.NET, also from the #Develop project).
Omer Raviv
+3  A: 

It is not directly possible to do this with the core .NET Framework. You need to use third party or add-on tools, for example:

bobbymcr
But why? Does the C# compiler don't use CodeDOM?
ulrichb
No, it does not. CodeDom is for managed application developers; csc.exe is unmanaged code which has no .NET dependencies.
bobbymcr
A: 

If you want the ability to parse, and carry out arbitrary analyses and transformations on C# source code (or a variety of other languages), check out our The DMS Software Reengineering Toolkit.

DMS has a full C# front end, builds complete abstract syntax trees for parsed code (but not a CodeDom), provides a full procedural API for walking/checking/changing the ASTs. After revising the tree, DMS can regenerate source code corresponding to the modified tree, either in fidelity mode where it tries to preserve the original spacing, or prettyprint mode where it applies a prettyprint style that you can control completely. Comments are retained in the regenerated source properly.

In addition, DMS provides source-level pattern matching and transformation (e.g, you can write "x=x+1 ==> x++" instead of coding all the walk-around-tree-to-verify, hack the tree to change.) See writeup on program transformations to understand what why this is a lot less work..

Ira Baxter