Alex
Alex

Reputation: 77359

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

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!

Upvotes: 10

Views: 878

Answers (3)

Jon Skeet
Jon Skeet

Reputation: 1503280

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.

Upvotes: 8

Marc Gravell
Marc Gravell

Reputation: 1064014

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.

Upvotes: 4

Sam Harwell
Sam Harwell

Reputation: 99989

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.

Upvotes: 0

Related Questions