Note that there are some explanatory texts on larger screens.

plurals
  1. POC# construct lambda using Expression.Call doesn't like certain types as params?
    text
    copied!<p>For various reasons I'm constructing a C# lambda dynamically using the expression tree facilities. e.g. I can make a Func&lt;string,bool&gt; at runtime as shown in the following snippet. </p> <pre><code> public static bool myMethod( object obj ) { … } // Construct a Func&lt;string,bool&gt; var myMethod = GetType().GetMethod("myMethod"); var lambdaParams = new ParameterExpression[] {Expression.Parameter(typeof (string))}; var callMyMethod = Expression.Call(myMethod, lambdaParams); var lambda = Expression.Lambda(typeof(Func&lt;string,bool&gt;), callMyMethod, lambdaParams); var del = (Func&lt;string,bool&gt;)lambda.Compile(); del("foo"); // works </code></pre> <p>However if I use the same code to try to make a Func&lt;int,bool&gt; or a Func&lt;DateTime,bool&gt; it blows up where indicated with the following strange exception:</p> <pre><code> // Construct a Func&lt;DateTime,bool&gt; or perhaps a struct type fails... why? var myMethod = GetType().GetMethod("myMethod"); var lambdaParams = new ParameterExpression[] {Expression.Parameter(typeof (DateTime))}; var callMyMethod = Expression.Call(myMethod, lambdaParams); // Blows up here… System.ArgumentException: Expression of type 'System.DateTime' cannot be used for parameter of type 'System.Object' of method 'Boolean myMethod(System.Object)' </code></pre> <p>So, string works and List&lt;string&gt; works but int32 does not work nor does DateTime. What is going on? I don't know how the deep internals of C# work but I am guessing it's due to int really being handled as a primitive and maybe DateTime (being a struct) as well...</p> <p>Any help with this would be greatly appreciated.</p> <p>thanks, Pat</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload