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 ?
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With