Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET - dump statement lambda body to string

Tags:

c#

.net

lambda

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

like image 222
Maxim Gueivandov Avatar asked Feb 07 '11 14:02

Maxim Gueivandov


1 Answers

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.

like image 100
CodesInChaos Avatar answered Sep 22 '22 06:09

CodesInChaos