views:

529

answers:

2

I am writing a fairly simple code gen tool, and I need the ability to convert MSIL (or MethodInfo) objects to their C# source. I realize Reflector does a great job of this, but it has the obnoxious "feature" of being UI only.

I know I could just generate the C# strings directly, using string.Format to insert the variable portions, but I'd really prefer to be able to generate methods programatically (e.g. a delegate or MethodInfo object), then pass those methods to a writer which would convert them to C#.

It seems a little silly that the System libraries make it so easy to go from a C# source code string to a compiled (and executable) method at runtime, but impossible to go from an object to source code--even for simple things.

Any ideas?

A: 

The code generators which I wrote as part of our application use String.Format, and although I am not entirely happy with String.Format (Lisp macros beat it any time of the day) it does the job all right. The C# compiler is going to re-check all your generated methods anyway, so you gain nothing by round-tripping through Reflection.Emit and the (still unwritten) MSIL-to-C# decompiler.

PS: why not use CodeDOM if you want to use something heavyweight?

Anton Tykhyy
+1  A: 

This add-in for Reflector lets you output to a file, and it is possible to run Reflector from the command line. It's probably simpler to get that to do what you want than to roll your own decompiler.

Anakrino is another decompiler with a command line option, but it hasn't been updated since .NET 1.1. It's open source, though, so you might be able to base your solution on it.

RossFabricant