title: How to unload assembly created by CSharpCodeProvider?
body: <h1>Problem</h1>
  
  <p><a href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.csharp.csharpcodeprovider?view=netframework-4.8" rel="nofollow noreferrer">CSharpCodeProvider</a> can be used to compile source .cs files into an assembly.
  However, the assembly is automatically loaded into the AppDomain.CurrentDomain by default. In my case, this is a problem because I need to be able to re-compile the assembly again during runtime, and since it's already loaded in the CurrentDomain, I can't unload that, so I'm stuck.</p>
  
  <p>I have looked through the docs and there seems to be no way to set the target app domain. I have also tried searching it on Google and only found answers where Assembly.Load was used, which I don't think I can use because I need to compile from raw source code, not a .dll</p>
  
  <p>How would one go about doing this? Are there any alternatives or workarounds?</p>
  
  <p><strong>Main program</strong></p>
  
  <pre class="lang-cs prettyprint-override"><code>using (var provider = new CSharpCodeProvider())
  {
    param.OutputAssembly = "myCompiledMod"
    var classFileNames = new DirectoryInfo("C:/sourceCode").GetFiles("*.cs", SearchOption.AllDirectories).Select(fi =&gt; fi.FullName).ToArray();
    CompilerResults result = provider.CompileAssemblyFromFile(param, classFileNames);
    Assembly newAssembly = result.CompiledAssembly // The assembly is already in AppDomain.CurrentDomain!
    // If you try compile again, you'll get an error; that class Test already exists
  }
  </code></pre>
  
  <p><strong>C:/sourceCode/test.cs</strong></p>
  
  <p><code>public class Test {}</code></p>
  
  <hr>
  
  <h1>What I tried already</h1>
  
  <p>I already tried creating a new AppDomain and loading it in there. What happens is the assembly ends up being loaded in both domains.</p>
  
  <pre class="lang-cs prettyprint-override"><code>// &lt;snip&gt;compile code&lt;/snip&gt;
  Evidence ev = AppDomain.CurrentDomain.Evidence;
  AppDomain domain = AppDomain.CreateDomain("NewDomain", ev);
  domain.Load(newAssembly);
  </code></pre>