I am working on an application where we need to log entire statement of anonymous (lambda) function.
What it means is that the "LogAction" method should log all the statements that are passed as action.
protected void LogAction(Action action)
{
/*
Log the statement(s) passed to this method i.e. should print
var a = 10;
var b = 20;
Console.WriteLine($"Sum of {a} and {b} is {a+b}");
*/
}
LogAction(() =>
{
var a = 10;
var b = 20;
Console.WriteLine($"Sum of {a} and {b} is {a+b}");
});
You can use the Expression class in C#:
The above code will print
() => WriteLine("Hello world")on the console. This should help enough for debugging purposes. Unfortunately it does not provide as much flexibility as one would expect. For example the following initialization will give you an error:A way around this is to define a method which you can later on assign to the Expression object:
Valid assignment:
The above code prints
() => Sum()on the console.