Thursday, May 3, 2007

Fun with Lambda.Compile: Code? Data?

Another very funky twist of C# 3.0 new features: in the following code snippet, tell what’s code (I.E. MSIL), what’s data (I.E. expression tree) and when the “data” gets compiled into “code”. (By the way, Today happens to be May 3rd, 2007).

Expression<Func<int,

    Expression<Func<int, int>>>> expr1

        = (a => (b => a + b * 3));

 

Expression<Func<int, int>> expr2 =

    expr1.Compile().Invoke(DateTime.Today.Day);

 

Func<int, int> func = expr2.Compile();

Console.WriteLine(func(10));

In case you have no clue, look into the structure of expr1 and expr2 might help:

No wonder LambdaExpression.Compile is Don Box’s favorite in C# 3.0.

Having fun…