7

Given the following statement lambda example:

var fMyAction = new Action(() =>
 {
    x += 2;
    something = what + ever; 
 });

What are possible ways to get the body of that lambda and dump it to string? (Something that will ultimately allow to write an extension method for Action class of this kind: fMyAction.Dump() which will return "x += 2; something = what + ever;").

Thanks

Maxim Gueivandov
  • 2,370
  • 1
  • 20
  • 33
  • What is it for? Please give more background on your question, probably there is a completely different solution. What you're trying to do now is almost impossible and does not make any sense in C-sharp. – SK-logic Feb 07 '11 at 14:54
  • 1
    @SK-logic: That would be definitely out of the scope of this specific post to discuss my own reasons on abstract level. – Maxim Gueivandov Feb 07 '11 at 16:16
  • you won't get a useful answer without explaining at least why do you need a string representation, how close this string should be to an original source, and what are your performance requirements. There are several options available besides decompilation. – SK-logic Feb 07 '11 at 16:23
  • @SK-logic: thank you for your interest, but I think I've got quite a useful answer to my quite a straightforward question – Maxim Gueivandov Feb 07 '11 at 19:04
  • [mono.linq.expressions](http://evain.net/blog/articles/2010/06/23/mono-linq-expressions/) does this, but then its only meant for expression trees. Another related question: [serializing-and-deserializing-expression-trees-in-c-sharp](http://stackoverflow.com/questions/217961/serializing-and-deserializing-expression-trees-in-c-sharp) – nawfal Dec 19 '13 at 19:04

2 Answers2

11

It's not possible in that form. Your lamda gets compiled to byte-code. While in theory it's possible to decompile the byte-code, just like reflector does, it's difficult, error prone and doesn't give you the exact code you compiled, but just code that's equivalent.

If you use an Expression<Action> instead of just Action you get the expression tree describing the lamda. And converting an expression tree to a string is possible(and there are existing libraries which do it).

But that's not possible in your example because it's a multi statement lamda. And only simple lamdas can be automatically converted to an expression tree.

Community
  • 1
  • 1
CodesInChaos
  • 106,488
  • 23
  • 218
  • 262
  • You are right... I found this and was ready to open champagne: http://code.msdn.microsoft.com/exprserialization Then all of a sudden: http://msdn.microsoft.com/en-us/library/bb397745.aspx – Maxim Gueivandov Feb 07 '11 at 16:37
0

Read through the tutorial here,

http://blogs.msdn.com/b/mattwar/archive/2007/07/30/linq-building-an-iqueryable-provider-part-i.aspx

Pay close attention to the visitor pattern he uses to walk a given expression tree. You should be able to alter it to fit your needs easy enough.

asawyer
  • 17,642
  • 8
  • 59
  • 87