Saturday, March 20, 2010

Dynamically Compiling F# in .NET

If you've ever needed to dynamically compile C# or VB.NET code in your program, you've likely seen and/or used the CodeDomProvider class. However, if you try to use this class to compile F# code, you will get a ConfigurationErrorsException with the following message: "There is no CodeDom provider defined for the language."

To compile F# code dynamically, you will need to use the FSharpCodeProvider class. Using it is hardly different from using the CodeDomProvider class

First, you need to add the following reference:
FSharp.Compiler.CodeDom.dll


Then add the following using statements:
using System.CodeDom.Compiler
using Microsoft.FSharp.Compiler.CodeDom;

The code is below.
public static void CompileFSharp(string sourceCode)
{
CompilerResults compilerResults;
CompilerParameters compilerParameters = new CompilerParameters();

compilerParameters.GenerateExecutable = true;
compilerParameters.OutputAssembly = "FSharpExecutable.exe";

var fsharpCodeProvider = new FSharpCodeProvider();
compilerResults = fsharpCodeProvider.CompileAssemblyFromSource(compilerParameters, sourceCode);

if(compilerResults.Errors.HasErrors)
{
// Handle compiler errors
}
}

If I have made any mistakes in the post, please do not hesitate to inform me about them.

No comments:

Post a Comment