3

I have some class ( simple class ) and i want to compile in runtime this class and create ( in runtime ) some dll that will contain this class.

Is there some way to do it ?

Thanks.

Yanshof
  • 9,659
  • 21
  • 95
  • 195
  • 1
    Use `CSharpCodeProvider`, this could be helpful: http://msdn.microsoft.com/en-gb/library/microsoft.csharp.csharpcodeprovider.aspx – davioooh Feb 28 '12 at 08:25
  • 2
    Have a look at: http://stackoverflow.com/questions/604501/generating-dll-assembly-dynamically-at-run-time – Davide Piras Feb 28 '12 at 08:29

2 Answers2

7

Yes, use CSharpCodeProvider.

You can read the sample code for "Snippy" that I used for C# in Depth - it does exactly this sort of thing.

You can ask CSharpCodeProvider to write to a file or build the assembly in memmory.

Sample code:

using System;
using System.CodeDom.Compiler;
using Microsoft.CSharp;

class Test
{
    static void Main()
    {
        var provider = new CSharpCodeProvider();
        var options = new CompilerParameters {
            OutputAssembly = "Foo.dll"
        };
        string source = "public class Foo {}";

        provider.CompileAssemblyFromSource(options, new[] { source });
    }
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

You can use the CSharpCodeProvider to complile code at run time. See this MSDN blog.

PS. Found by a quick google search ;)

Alexander R
  • 2,468
  • 24
  • 28