Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compiling with CodeDomProvider doesn't allow new features of C# or VB

I'm compiling some C# and VB code at run time using the CodeDomProvider, CompilerInfo, and CompilerParameters. It works great, and I really like being able to add scripting support to my application, but it only seems to support .NET 2.0 syntax. For example, the var keyword isn't supported in C#, and the If(bool, string, string) expression isn't supported in VB.

How can I tell it to target the 3.5 framework?

like image 231
Don Kirkby Avatar asked Dec 19 '08 00:12

Don Kirkby


2 Answers

OK, I found a big hint here from Anders Norås that there is a constructor for the CSharpCodeProvider constructor that takes some options, including the compiler version. When I checked the MSDN docs, I found that it's cleaner to specify the compiler options in the App.config file. Here's an example:

<system.codedom>
  <compilers>
    <compiler
      language="vb;vbs;visualbasic;vbscript"
      extension=".vb"
      type="Microsoft.VisualBasic.VBCodeProvider, System, 
        Version=2.0.3600.0, Culture=neutral, 
        PublicKeyToken=b77a5c561934e089"
      compilerOptions="/optimize"
      warningLevel="1" >
      <providerOption
        name="CompilerVersion"
        value="v3.5" />
    </compiler>
    <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="v3.5" />
    </compiler>
  </compilers>
</system.codedom>

My only disappointment is that now I get two versions of each compiler from CodeDomProvider.GetAllCompilerInfo(). The configuration documentation says that the App.config should override the machine.config settings, but I get both. So far, the App.config is always after the machine.config, so I just let the later ones override the earlier ones. Anybody know how to avoid the duplication?

like image 134
Don Kirkby Avatar answered Oct 28 '22 20:10

Don Kirkby


Not sure where you are going with the app.config's but heres how you can tell it to use 3.5 framework.

var csc = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v3.5" } });

http://blogs.msdn.com/lukeh/archive/2007/07/11/c-3-0-and-codedom.aspx

like image 34
Cwoo Avatar answered Oct 28 '22 19:10

Cwoo