Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# print a delegate

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 ?

like image 390
Toto Avatar asked Oct 15 '09 13:10

Toto


2 Answers

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.

like image 181
Vitaliy Liptchinsky Avatar answered Oct 18 '22 04:10

Vitaliy Liptchinsky


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).

like image 30
Marc Gravell Avatar answered Oct 18 '22 03:10

Marc Gravell