How to compile C# 3.0 code dynamically
One of major features being shipped with Visual Studio 2008 was new version of C# language.
When one creates new C# project in Visual Studio 2008 it can choose target framework version, which enables functionality/IntelliSense targeted to selected framework. But how some runtime generated code could be compiled with specific framework target?
In .NET v3.5 we got new overload to CSharpCodeProvider class, which takes "providerOptions" argument. This argument type is IDictionary<string, string> which could be used co configure compiler properties. Here is code sample, how to compile some basic runtime generated LINQ query:
var csc = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v3.5" } });
var parameters = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll" }, "test.exe", true);
parameters.GenerateExecutable = true;
CompilerResults results = csc.CompileAssemblyFromSource(parameters,
@"using System.Linq;
using System;
class Program
{
public static void Main(string[] args)
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var numsPlusOne =
from n in numbers
select n + 1;
Console.WriteLine(""Numbers + 1:"");
foreach (var i in numsPlusOne)
Console.WriteLine(i);
Console.ReadLine();
}
}");
Console.WriteLine("Compilation results:\n================================");
results.Errors.Cast<CompilerError>().ToList().ForEach(error => Console.WriteLine(error.ErrorText));
Console.WriteLine("Done.");
The main think here is "CompilerVersion" & "v3.5" parameter passed to code provider.
This also could be controlled via .config file like follows:
<configuration>
<system.codedom>
<compilers>
<!-- zero or more compiler elements -->
<compiler
language="c#;cs;csharp"
extension=".cs"
type="Microsoft.CSharp.CSharpCodeProvider, System,
Version=2.0.3600.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089"
compilerOptions="/optimize"
warningLevel="1" />
<providerOption
name="CompilerVersion"
value="3.5" />
</compilers>
</system.codedom>
</configuration>
Enjoy.