Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# .NET 3.5: What is Expression<> used for?

Tags:

c#

expression

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!

like image 607
Alex Avatar asked Sep 15 '09 05:09

Alex


2 Answers

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.
like image 184
Jon Skeet Avatar answered Oct 12 '22 00:10

Jon Skeet


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):

  • generic operators
  • object cloning
  • complex initialization
  • object comparison

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.

like image 23
Marc Gravell Avatar answered Oct 12 '22 01:10

Marc Gravell