Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Body from Func<T>

how can I get a body from function

Func<bool> methodCall = () => output.SendToFile(); 

if (methodCall())
    Console.WriteLine("Success!");

I need to get this output.SendToFile() as a string

Another example:

string log = "";

public void Foo<T>(Func<T> func)
{
    try
    {
        var t = func();
    }
    catch (Exception)
    {
        //here I need to add the body of the lambda
        // log += func.body;
    }
}

public void Test()
{
    var a = 5;
    var b = 6;
    Foo(() => a > b);
}

Edit: For more information on this topic see: Expression Trees

like image 482
Sergey Avatar asked Jul 16 '13 10:07

Sergey


1 Answers

You can't. A Func<T> is nothing you can easily analyze. If you want to analyze a lambda, you need to create a Expression<Func<bool>> and analyze it.

Getting the body of an expression is simple:

Expression<Func<bool>> methodCall = () => output.SendToFile(); 
var body = methodCall.Body;

body would be a MethodCallExpression you could further analyze or just output via ToString. Using ToString won't result exactly in what you would like to have, but it contains that information, too.

For example, executing ToString() on body in LINQPad results in something like this:

value(UserQuery+<>c__DisplayClass0).output.SendToFile()

As you can see, "output.SendToFile()" is there.

To actually execute the code defined by an expression, you first need to compile it:

var func = methodCall.Compile();
func();

Which can be shortened to this:

methodCall.Compile()(); // looks strange but is valid.
like image 100
Daniel Hilgarth Avatar answered Nov 09 '22 02:11

Daniel Hilgarth