C# anonymous function log method body

349 Views Asked by At

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}");
        });
1

There are 1 best solutions below

0
dimitar.d On

You can use the Expression class in C#:

Expression<Action> ex = () => System.Console.WriteLine("Hello world");

Console.WriteLine(ex.ToString());

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:

//ERROR: A lambda expression with a statement body cannot be converted to an expression tree
Expression<Action> ex = () => 
            {
                int a = 10;
                int b = 21;
                Console.WriteLine(a + b);
            };

A way around this is to define a method which you can later on assign to the Expression object:

void Sum()
        {
            int a = 10;
            int b = 21;
            Console.WriteLine(a + b);
        }

Valid assignment:

Expression<Action> ex = () => Sum();
Console.WriteLine(ex.ToString());

The above code prints () => Sum() on the console.