0

Using Linq.Expression<T> types we can programmatically define AST for later evaluation and/or execution.

But in practical terms, what are the implications of defining the method signature in this way:

public void SomeMethod1(Func<bool> func) { ... } // 1.

instead of

public void SomeMethod2(Expression<Func<bool>> expr) { ... } // 2.

Clearly the way we get the result from Func<bool> varies from:

var result = func(); // 1.

to

var func = expr.Compile() // 2.
var result = func();

At raw practical level also invocation is similar:

SomeMethod1(() => true); // A.
SomeMethod1(() => AMethodReturnsABool()); // B.
SomeMethod1(AMethodReturnsABool); // C.

with the difference that SomeMethod2 at compile level don't accept the method-group syntax:

//SomeMethod2(AMethodReturnsABool); // -> don't compile

When I need to define a signature with standard delegates Action<T,...> or Func<T,..> when I should define them inside an Expression<T>?

jay
  • 1,510
  • 2
  • 11
  • 19
  • IMHO , Till you don't write a software which generates code by drag & drop. In most practical terms , you don't need it – TalentTuner Mar 21 '13 at 10:30
  • 2
    See this question http://stackoverflow.com/questions/793571/why-would-you-use-expressionfunct-rather-than-funct – Fendy Mar 21 '13 at 10:40
  • @Fendy +1, thanks for the link. I've tried to search, but I missed this question. – jay Mar 21 '13 at 11:34

1 Answers1

0

Easy. If you don't need to have access to the AST of your LINQ expression, use the compiled (anonymous delegate) version.

The cases that I think of where you may need to have access to the AST:

  • Transforming the AST into something else, like an SQL where clause.
  • Analyze some properties of the written code.
  • Programatically build a delegate. For instance, build Expression<T> objects out of some user input. This can save the hassle of writing your own AST with its IL translator.
  • Astracting your Data Access Layer to be able to use either LinqToSQL or a simple in-memory list with the same LINQ query specifications.

In short, if you don't need Expression<T>, don't use Expression<T>.

Laurent LA RIZZA
  • 2,905
  • 1
  • 23
  • 41