6

I can compile, get an instance and invoke a method of any C# type programmaticaly. There lots of info on that, including the StackOverflow (How can I evaluate a C# expression dynamically?). My problem is that I'm in the web environment and cannot save anything to /bin directory. I can compile "in-memory" as the above mentioned link suggests but then I won't be able to "unload" my custom assembly from the current AppDomain. After a while that will become a huge memory problem.

Is it possible to open a new AppDomain, compile new assembly "in-memory", evaluate some expression or access some member of that assembly inside of that new AppDomain and kill that AppDomain safely when done, all that without saving anything to a hard drive?

General Grievance
  • 4,555
  • 31
  • 31
  • 45
Sasha
  • 83
  • 3
  • If you only need access to an arbitrary method of a known type (and not compilation of a more complex expression), you can use the GetMethod method of the Type class and Delegate.CreateDelegate. I'd try to avoid using a new AppDomain, if possible, as there can be a lot of new complexity to get the proper Marshaling. – Dan Bryant May 10 '10 at 18:57
  • I pretty much need to evaluate a C# expression on the fly. The same old bool r = Eval("3>2"); where the Eval is anything that would help me evaluating the bool without touching the disk. So, no, reflection alone won't help here. Thanks, though :) – Sasha May 10 '10 at 19:20

1 Answers1

2

Have you taken a look at the DynamicMethod type in .Net? This type creates garbage collection enabled in memory methods using Reflection.Emit. This sounds like exactly what you're looking for.

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
  • I entirely missed the whole DynamicMethod thing. Reading already... Still can't see how to use it to evaluate a simple thing like b = Evaluate("5 < 6"). Looking more, hoping I just miss something. Thank you! – Sasha May 10 '10 at 19:23