2. About me
Vedran Maršić AKA Fosna
dev at http://www.axilis.com/author/vmarsic/
organizing programming workshops for kids
Logo, Scratch, HTML, CSS, JavaScript, Python, C++
3. We’ll cover
Part 1
What is expression tree in C#
How is it different from similar looking lambda delegates
How to build expression trees
How to parse expression trees
Where are you already using them
Part 2
Check out few expression tree exploits
Point to brilliant, not easy to understand, ideas or projects from some cool developer
maniacs
4. We won’t cover
Implementing LINQ providers
Implementing deep copy
Implementing faster static dictionary
Implementing IoC container
6. Expression Tree Nodes
Plain old C#
• c = a + b
Lambda expression
• (a, b) => a + b
Gists:
AddStatement.linq
SimpleBinaryExpression.linq
7. Definition
represent code in a tree-like data structure
not in MSIL (Microsoft Intermediate Language)
each node is an expression
has compiler smell all over it
can compile to get functions!
get some good ol’ MSIL
MSIL ex:
IL_0007: ldloc.0 // a
IL_0008: ldloc.1 // b
IL_0009: add
IL_000A: stloc.2 // c
14. Applied Expression Trees Vs Lambda Delegates
Which technology exploits expression trees and which one doesn’t?
LINQ to Objects
LINQ to Entities (EF)
LINQ to XML
Parallel LINQ
15. How to Create an Expression Tree?
From lambda expression at compile time
Method invocation flavor
Query syntax
Using Expression API at run time
Why would anyone do that?
Gist: BuildExp.linq
17. Lazy: AsEnumerable()
If code can be executed in process then the job can be done with the
simple type called IEnumerable<T>
remember yield return
18. Lazy: AsQueryable()
If you need to translate a query expression into a string that will be passed
to another process, then use IQueryable<T> and expression trees.
22. Resources
Start with
http://stackoverflow.com/a/403233/953338
Expression Tree Basics, Charlie Calvert 31 Jan 2008 3:49 AM
http://blogs.msdn.com/b/charlie/archive/2008/01/31/expression-tree-basics.aspx
Published by Olexander Ivanitskyi on Tuesday, June 11, 2013
LINQ: Func<T> vs. Expression<Func<T>>
http://ivanitskyi.blogspot.hr/2013/06/linq-func-vs-expression.html
asked Apr 27 '09 at 13:50, Richard Nagle
Why would you use Expression<Func<T>> rather than Func<T>?
http://stackoverflow.com/questions/793571/why-would-you-use-expressionfunct-
rather-than-funct