Precompiled LINQ Expression delegates by compiler

Topics: C# Language Design
Nov 12, 2014 at 4:46 PM
Edited Nov 12, 2014 at 4:48 PM
I try to refactor any occurence of repeated LINQ code into reusable expressions:
public class ModelEntity
{
  public static readonly Expression<Func<ModelEntity, string>> UniqueKeyExpression =
    e => e.P1 + ":" + e.P2;
}
In combination with LinqKit/ExpressionBuilder no problems so far.

Now here and then I have to fill dictionaries so I declare another member:
  public static readonly Func<ModelEntity, string> UniqueKeyFunc = UniqueKeyExpression.Compile();
This of course works, too, but has 2 disadvantages:
  • it is compiling code when the static class constructor runs.
  • it is executing dynamic code.
In my opinion the compiler could already compile the expression to an anonymous static method and return the delegate:
  public static readonly Func<ModelEntity, string> UniqueKeyFunc = funcof(UniqueKeyExpression);
I could also live with a real or compiler-faked dual type which gets initialized once and which contains both the expression and the delegate:
public class ModelEntity
{
  private template DualExpression<ModelEntity, string> uniqueKey = e => e.P1 + ":" + e.P2;

  public static readonly Expression<Func<ModelEntity, string>> UniqueKeyExpression = uniquekey.Expression;

  public static readonly Func<ModelEntity, string> UniqueKeyFunc = uniqueKey.Delegate;
}
Thats just an idea, maybe a syntax which makes more clear that it is compiler magic could be "expressionof(uniquekey)" and "delegateof(uniquekey)".

I just hate it to implement critical code more than once, because most of the time when changing things later you only change 3 occurences of 4 places where identical/similar code had been used.
Nov 12, 2014 at 10:20 PM
Why is "executing dynamic code" a disadvantage?
Nov 15, 2014 at 9:06 PM
Edited Nov 15, 2014 at 9:06 PM
Why is "executing dynamic code" a disadvantage?
1) It increases the startup time
2) You can't use Expression.Compile on platforms like iOS
Nov 15, 2014 at 9:20 PM
I really like your idea. We currenlty have a Evaluate method that compiles + caches + invokes the resulting lambda, but all this could be a completely done at compile time.