0

I am using CSharpCompilation.Create to create assembly from scratch. The thing I got to know is this always creates a new assembly. Is there anyway to add/modify the existing DLL in Roslyn? This is because I am building a tool where a user can type C# code in richtextbox and compile it to add it to the existing assembly. Is it possible, if not what I am doing wrong and what is the right way?

P.S.,

I have also tried CSharpCodeProvider as well to compile the code, but it is also Generating assembly with only the code I typed in richtextbox. The output assembly did not have other classes in that.

coding_cs
  • 77
  • 9
  • 1
    What's the reason that the new code must be in the same assembly? If it is really required, you could compile to a new assembly and then merge using [ILMerge](https://github.com/dotnet/ILMerge). Or - whar's basically the same - disassemble (ildasm) the existing one to IL, add your code and assemble again (ilasm). – Klaus Gütter Feb 15 '22 at 14:28
  • Yes I need the new code to be part of same assembly. Is there any way to do this how Visual Studio does? If we add a class and compile in VS, it will be added to same assembly. I need something similar. And everything should be done programmatically. – coding_cs Feb 15 '22 at 14:42
  • Visual Studio has all the source code and will compile everything anew. – Klaus Gütter Feb 15 '22 at 14:43
  • Can we do it programmatically in similar way? – coding_cs Feb 15 '22 at 14:45
  • Read my comment again: VS does *not* take one input assembly and add newly compiled code to it (what you want to do). VS *will* compile everything and output it to a new assembly (which requires the complete source code). – Klaus Gütter Feb 15 '22 at 14:48
  • as you said we can merge multiple assemblies ILMerge, ILMerge is deprecated. You said another way. Can you please provide some existing examples for what you have mentioned? – coding_cs Feb 15 '22 at 15:55
  • Your use case is still unclear. "I need the new code to be part of same assembly" - why? – Klaus Gütter Feb 15 '22 at 17:14
  • Yes because I am delivering this assembly to the end-user and they will use the types inside this assembly to extend and create new types. Why I cant have new assembly for each class is, I have number of classes lets say 100, I cant have individual assembly for each of them. – coding_cs Feb 15 '22 at 18:16

1 Answers1

1

Yes as mentioned in comment by Klauss Gutter, you have to build the assembly individually and merge it later using ILMerge. I know ILMerge is out of support and is deprecated. You can use ILRepack to do this. It provides the same functionality as ILMerge.

You can use NuGet Package to install ILRepack first and then add reference to the ILRepack.exe to your project to use its methods to pack multiple assemblies in to one.

Roslyn or CSharpProvider wont help you to merge your assemblies. The main motto of these are to compile and create an assembly not merge.

harsha.cs
  • 122
  • 2
  • 13