background preloader

Expression trees

Facebook Twitter

To Bind or Not To Bind – Dynamic Expression Trees – Part 1. Tuesday, August 26, 2008 10:40 PM bart In the previous post, I outlined the use of the expression trees from the System.Linq.Expressions namespace. Let’s recap to set the scene: Expression<Func<string, int, int, string>> data = (string s, int a, int b) => s.Substring(a, b); produces (deep breadth) ParameterExpression s = Expression.Parameter(typeof(string), “s”); ParameterExpression a = Expression.Parameter(typeof(int), “a”); ParameterExpression b = Expression.Parameter(typeof(int), “b”); Expression<Func<string, int, int, string>> data = Expression.Lambda<Func<string, int, int, string>>( Expression.Call(s, typeof(string).GetMethod(“Substring”, new Type[] { typeof(int), typeof(int) }), a, b), s, a, b ); Func<string, int, int, string> fun = data.Compile(); Console.WriteLine(fun(“Bart”, 1, 2)); where I’ve indicated all the strong typing using underlines.

So what do we want to try now? Class Bar { public Foo Substring(long a, long b) { … } } So, how does this look like? Dynamic Expression API. Database applications frequently rely on “Dynamic SQL”—queries that are constructed at run-time through program logic. The LINQ infrastructure supports similar capabilities through dynamic construction of expression trees using the classes in the System.Linq.Expressions namespace. Expression trees are an appropriate abstraction for a variety of scenarios, but for others a string-based representation may be more convenient.

The Dynamic Expression API extends the core LINQ API with that capability. The API is located in the Dynamic.cs source file and provides · Dynamic parsing of strings to produce expression trees (the ParseLambda and Parse methods), · Dynamic creation of “Data Classes” (the CreateClass methods), and · Dynamic string-based querying through LINQ providers (the IQueryable extension methods). The Dynamic Expression API relies on a simple expression language for formulating expressions and queries in strings. var query = db.Customers. The ParseLambda Methods The example Literals.