1

I use VBCodeProvider to compile code, but it generates a new assembly, and also I need to add all references to assemblies I need to use.

Is there a way to compile code in the current assembly?

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Aram Gevorgyan
  • 2,175
  • 7
  • 37
  • 57
  • 1
    No, there isn't. What are you trying to do? And why did you tag your question with both C# and VB.NET? – Luaan Sep 21 '15 at 13:41
  • @Luaan: I need to compile code several times and I don't want to create new assembly and adding all references for each time, I just want to compile in current assembly if it were possible. Because both C# and VB.Net answers are acceptable for me. – Aram Gevorgyan Sep 22 '15 at 07:21
  • If it's good enough for ASP.NET, why isn't it good enough for you? And why would you care about "adding all the references each time"? What do you imagine goes on when you do that? – Luaan Sep 22 '15 at 07:54
  • @Luaan: It is good, if there are no way. Of course it would be better not to generate new assembly each time, I just wanted to know. – Aram Gevorgyan Sep 22 '15 at 08:01
  • But *why* do you think it would be better? What's wrong with generating new assembly each time? Did you measure some performance impact (doubtful, compared to the cost the old code providers have for the compilation itself - they simply run `csc` etc.)? Or is it just some religious objection to having too many assemblies? – Luaan Sep 22 '15 at 08:08
  • I think it would be more memory consuming. – Aram Gevorgyan Sep 22 '15 at 08:21
  • 1
    "Thinking" doesn't get you far when considering performance implications. It took me 5 minutes to write a test project, and creating thousands of individual assemblies requires tiny amounts of memory compared to the compilation itself. Ten thousand assemblies take less than 50 MiB (it's hard to isolate *all* the irrelevant memory usage, it's probably considerably less than 50 MiB). If that's too much for you, you can use the old assembly when building the new one, and replace it rather than keeping multiple dynamic assemblies in memory at once, but there's probably lots to improve before that. – Luaan Sep 22 '15 at 08:59

2 Answers2

2

VBCodeProvider is obsolete. Use Roslyn. But that still will not allow you to amend an existing assembly at runtime because it's not possible.

Compile and load a new assembly. You can use Reflection to automatically add a list of references to a Roslyn compilation.

usr
  • 168,620
  • 35
  • 240
  • 369
1

You cannot temper the current assembly.

A couple of years ago, I have written an on the topic of dynamic compilation: http://emoreau.com/Entries/Articles/2011/07/Compiling-code-on-the-fly.aspx

BTW, Roslyn is only available if you are using VS2015 (unless you are using the CTPs that were available for VS2013 but it is not a good idea for anything else then testing).

emoreau99
  • 634
  • 6
  • 16