ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

CSharpCompile

Compiles a string into an assembly. .NET 4

Source

public static CompilerResults CSharpCompile(this string code, string dllName = "dynamicCompile", params string[] additionalAssemblies)
{
    var csc = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v4.0" } });
    var parameters = new CompilerParameters
    {
       ReferencedAssemblies = {
          "mscorlib.dll",
          "System.Core.dll",
       },
       OutputAssembly = dllName,
       GenerateExecutable = false,
       GenerateInMemory = true,
    };

    parameters.ReferencedAssemblies.AddRange(additionalAssemblies);

    return csc.CompileAssemblyFromSource(parameters, code);
}

Example

var results = @"include System;

public class Example1
{
   public string Prop { get; set; }
}".CSharpCompile();

Author: Dan Gidman

Submitted on: 17 nov. 2011

Language: C#

Type: System.String

Views: 6711