0 Comments

I was battling yesterday with Lambda Expressions. I wanted to get the function’s parameter’s value out in a usable form (object). Here’s how you can do it:

<span style="color: #606060" id="lnum1">   1:</span> <span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span> Run()

<span style="color: #606060" id="lnum2">   2:</span> {

<span style="color: #606060" id="lnum3">   3:</span>     System.Linq.Expressions.Expression&lt;System.Func&lt;DateTime&gt;&gt; f2 = () =&gt; DateTime.Now.AddDays(12345);

<span style="color: #606060" id="lnum4">   4:</span>  

<span style="color: #606060" id="lnum5">   5:</span>     MethodCallExpression call = (MethodCallExpression)f2.Body;

<span style="color: #606060" id="lnum6">   6:</span>     ConstantExpression arg = (ConstantExpression)call.Arguments[0];

<span style="color: #606060" id="lnum7">   7:</span>  

<span style="color: #606060" id="lnum8">   8:</span>     var <span style="color: #0000ff">value</span> = GetValue(arg);

<span style="color: #606060" id="lnum9">   9:</span>     Debug.WriteLine(<span style="color: #0000ff">value</span>);

<span style="color: #606060" id="lnum10">  10:</span> }

<span style="color: #606060" id="lnum11">  11:</span>  

<span style="color: #606060" id="lnum12">  12:</span> <span style="color: #0000ff">private</span> <span style="color: #0000ff">object</span> GetValue(ConstantExpression expression)

<span style="color: #606060" id="lnum13">  13:</span> {

<span style="color: #606060" id="lnum14">  14:</span>     Expression conversion = Expression.Convert(expression, <span style="color: #0000ff">typeof</span>(<span style="color: #0000ff">object</span>));

<span style="color: #606060" id="lnum15">  15:</span>     var getterLambda = Expression.Lambda&lt;Func&lt;<span style="color: #0000ff">object</span>&gt;&gt;(conversion);

<span style="color: #606060" id="lnum16">  16:</span>  

<span style="color: #606060" id="lnum17">  17:</span>     var getter = getterLambda.Compile();

<span style="color: #606060" id="lnum18">  18:</span>  

<span style="color: #606060" id="lnum19">  19:</span>     <span style="color: #0000ff">return</span> getter();

<span style="color: #606060" id="lnum20">  20:</span> }

Thanks goes to these and many other questions in StackOverflow: