tags:

views:

245

answers:

3

What exactly is Expression<> used for in C#? Are there any scenarios where you would instantiate Expression<>'s yourself as an object? If so, please give an example!

Thank you!

A: 

Take a look at my before & after code in my answer to another SO question.

Summary: Expression<> greatly simplified the code, made it easier to understand, and even fixed a phantom bug.

280Z28
+7  A: 

Expression<T> is almost entirely used for LINQ, but it doesn't have to be. Within LINQ, it's usually used to "capture" the logic expressed in code, but keep it in data. That data can then be examined by the LINQ provider and handled appropriately - e.g. by converting it into SQL. Usually the expression trees in LINQ are created by the compiler from lambda expressions or query expressions - but in other cases it can be handy to use the API directly yourself.

A few examples of other places I've used it and seen it used:

  • In MiscUtil, Marc Gravell used it to implement "generic arithmetic" - if a type has the relevant operator, it can be used generically.
  • In UnconstrainedMelody I used it in a similar way to perform operations on flags enums, regardless of their underlying type (which is trickier than you might expect, due to long and ulong having different ranges)
  • In Visual LINQ I used query expressions to "animate" LINQ, so you can see what's going on. While obviously this is a LINQ usage, it's not the traditional form of translating logic into another form.
Jon Skeet
where can i see 'VisualLINQ'?
flesh
Oops, meant to include a link to the blog post. Hang on...
Jon Skeet
+3  A: 

In terms of LINQ, there are things you can do to create more versatile LINQ queries at runtime than you can purely in lambdas.

I've used Expression many times as a micro-compiler, as an alternative to DynamicMethod and IL. This approach gets stronger in .NET 4.0 (as discussed on InfoQ), but even in 3.5 there are lots of things you can do (generally based on runtime data; configuration etc):

I also used it as part of a maths engine for some work I did with Microsoft - i.e. parse a math expression ("(x + 12) * y = z" etc) into an Expression tree, compile it and run it.

Another intersting use (illustrated by Jason Bock, here) is in genetic programming; build your candidates as Expression trees, and you have the necessary code to execute them quickly (after Compile()), but importantly (for genetic programming), also to swap fragments around.

Marc Gravell
Is there anywhere we can see the code you did for Microsoft? I'd really like to see some examples of this kind of thing ..
flesh
I have a copy, but I don't think it would be wise to post it "as is" (it is joint-owned by my employer and Microsoft). I'll try to find time to re-do from inception - it isn't much, I wrote the original on the train on the way to Microsoft's Reading HQ ;-p
Marc Gravell