Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Give the code below a run. I wanted to test your assumption that e => e.Location == location is compiling into something that can be constructed with Expression.Equal, Expression.Property, and Expression.Constant.</p> <pre><code> class Program { static void Main(string[] args) { var location = new Location(); Expression&lt;Func&lt;Employee, bool&gt;&gt; expression = e =&gt; e.Location == location; var untypedBody = expression.Body; //The untyped body is a BinaryExpression Debug.Assert( typeof(BinaryExpression).IsAssignableFrom(untypedBody.GetType()), "Not Expression.Equal"); var body = (BinaryExpression)untypedBody; var untypedLeft = body.Left; var untypedRight = body.Right; //The untyped left expression is a MemberExpression Debug.Assert( typeof(MemberExpression).IsAssignableFrom(untypedLeft.GetType()), "Not Expression.Property"); ////The untyped right expression is a ConstantExpression //Debug.Assert( // typeof(ConstantExpression).IsAssignableFrom(untypedRight.GetType()), // "Not Expression.Constant"); //The untyped right expression is a MemberExpression? Debug.Assert( typeof(MemberExpression).IsAssignableFrom(untypedRight.GetType()))); } } public class Employee { public Location Location { get; set; } } public class Location { } </code></pre> <p>It seems like it isn't, and its because the right expression isn't a Constant. To see this, uncomment the commented out code.</p> <p>What I don't understand is why the right expression is a MemberExpression. Perhaps someone who knows the linq expression compiler can shed more light onto this then I can.</p> <p>Edit: This may have to do with closure in lambdas - a class is created behind the scenes which contains the closed over variables. The location might then be a member of that class. I'm not sure about this, but it's what I suspect.</p> <p><a href="https://stackoverflow.com/questions/3991621/can-i-capture-a-local-variable-into-a-linq-expression-as-a-constant-rather-than">This post</a> may shed additional light on the situation.</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