Using the C# code provider and the ICodeCompiler.CompileAssemblyFromSource
method, I am attempting to compile a code file in order to produce an executable assembly.
The code that I would like to compile makes use of features such as optional parameters and extension methods that are only available when using the language C# 4.
Having said that, the code that I would like to compile only requires (and needs) to target version 2.0 of the .NET Framework.
Using the proceeding code it is possible to avoid any compile-time errors pertaining to syntax however, the resulting assembly will target version 4.0 of the framework which is undesirable.
var compiler = new CSharpCodeProvider(
new Dictionary<string, string> { { "CompilerVersion", "v4.0" } } );
How can I make is so that the code provider targets language version 4.0 but produces an assembly that only requires version 2.0 of the framework?
You need to instruct the C# compiler (that CSharpCodeProvider uses indirectly) that you want to link to another mscorlib.dll, using the /nostdlib option. Here is a sample that should do it:
If you run this, it should compile a program.exe file. If you run that file, it should display something like this: