views:

94

answers:

3

Is there a simple way to print the code of a delegate at runtime ? (that "contains one method").

public delegate void SimpleDelegate();

SimpleDelegate delegateInstance = 
           delegate { DoSomeStuff(); int i = DoOtherStuff() };

Now, I would like to display on the screen the body of delegateInstance. That is to say, doing something like reflector. Can I do this ? Maybe I can use some .pdb files ?

+3  A: 

You can print IL, that's it. Probably there is some reusable components in .NET Reflector that you could use to transform IL back to C# or VB.NET.

PDB files contain line numbers, non-public classes/structres/methods, variable names. If you have original C# source code at hand, you can try to get code from there by mapping with line numbers in PDB files.

Vitaliy Liptchinsky
A: 

I don't believe there is a simple way to accomplish this. Reflector or some other decompiler can show you the source of your program. As far as I know, the PDB only maps op codes to lines in the source of a program. It does not include the source.

I have used the StackTrace class along with the PDB and the source to be able to find out the source of an exception.

Jake Pearson
+3  A: 

Note that there are some cases where you can do something like this with lambdas, by compiling them to an Expression tree rather than a delegate (which is cheating, but may be enough to help):

    Expression<Func<char, int, string>> func
        = (c, i) => new string(c, i);
    Console.WriteLine(func); // writes: (c, i) => new String(c, i)
    var del = func.Compile();
    string s = del('a', 5);
    Console.WriteLine(s); // writes: aaaaa

Note that .NET 4.0 expression trees can encapsulate the statement bodies as per the original question (discussed at the end of this article) - but the C# compiler doesn't support compiling C# code to such expressions (you need to do it the hard way).

Marc Gravell
I so, so, so wish the C# 4 compiler took advantange of the full power of the new expression trees. :(
280Z28
I know this but expression are limited...
Toto
In 3.5 they are; not so in 4.0 - but I know what you mean.
Marc Gravell