3

How get a source code of anonymous method?

For example:

Func<Boolean> func = (() => DateTime.Now.Seconds % 2 == 0);

Console.WriteLine(GetSourceCode(func)); // must: DateTime.Now.Seconds % 2 == 0

String GetSourceCode<T>(Func<T> f) - ???
Horev Ivan
  • 270
  • 3
  • 9

1 Answers1

6

You can wrap it inside Expression and call ToString() on it and that will get you the source code.

Like this:

Expression<Func<Boolean>> func = (() => DateTime.Now.Seconds % 2 == 0);
var str = func.ToString();

The output str becomes () => DateTime.Now.Seconds % 2 == 0

Davor Zlotrg
  • 6,020
  • 2
  • 33
  • 51
  • +1 Awesome, didn't know about this! output is `() => DateTime.Now.Second % 2 == 0` – Daniel Imms Mar 02 '13 at 13:21
  • 1
    It's worth noting that technically this isn't a function. If you really do have a function you can't ever get it's source code as a string. – Servy Mar 26 '13 at 17:02