3

How would I convert a Func<T> into an Expression<Func<T>> without actually composing the expression myself? I want to do this for a known T, i.e. for a closed type.

For e.g.

class Person 
{
  public static Func<Person> Factory { get { return () => new Person(); } }

  public static Expression<Func<Person>> ToExpression(Func<Person> personFactory)
  {
    // this is what I am asking
  }
}
Water Cooler v2
  • 32,724
  • 54
  • 166
  • 336
  • 2
    I'm almost certain that you cannot. Would love to be proven wrong through. – Andrew Shepherd Aug 04 '14 at 00:23
  • 1
    Duplicates: http://stackoverflow.com/questions/3809823/reverse-of-expressionfunct-tresult-compile http://stackoverflow.com/questions/2305988/is-there-a-library-that-can-decompile-a-method-into-an-expression-tree-with-sup – Loathing Aug 04 '14 at 00:24
  • Thank you, @AndrewShepherd and @ Loathing. – Water Cooler v2 Aug 04 '14 at 00:26
  • Maybe you could find a disassembler ([ILSpy is a good one](http://ilspy.net/)), figure out how to use it as a library to turn the `Func<>`'s IL into C#, and then use a compiler to turn the C# into an `Expression<>`. Of course, not all `Func<>`s you might receive will work for you, but the simpler ones should be easy to convert. If you know you have a very small list of `Func`s, you might try disassembling it yourself: e.g. known patterns for calling a constructor or static method with constants only. – Tim S. Aug 04 '14 at 00:43
  • 2
    @WaterCoolerv2, an expression tree (`Expression>`) can be *compiled* into IL code (`Func`). This is (definitionally) a robust and reasonably straightforward process. The inverse requires a decompiler. It's almost inconceivable that the ultimate solution you are after will involve doing so in production code. Can you explain the reason you need this feature? Every time this situation has come up for me, I've been able to modify the code to consume an `Expression>` instead. (And remember, you can go from `Expression>` to `Func` with `expression.Compile()`) – Kirk Woll Aug 04 '14 at 00:49

0 Answers0