Monday, May 07, 2007

Runtime Code Compilation using .Net

Compiling code at run time, wow, doesn't that just extend the borders you can stretch with your program ?

Well, You can do exactly that with .Net's CSharpCodeProvider class (For C#). Lemme show it can be done.

// Create instance of C# Compiler
Microsoft.CSharp.CSharpCodeProvider codeProv = new Microsoft.CSharp.CSharpCodeProvider();
System.CodeDom.Compiler.ICodeCompiler cSharpCompiler = codeProv.CreateCompiler();


// Add the references that is needed for compiling code
System.CodeDom.Compiler.CompilerParameters compilerParams = new System.CodeDom.Compiler.CompilerParameters(ReferencedAssemblys);


// Set the options like whether to generate the exe in disk or keep it in memory
compilerParams.GenerateExecutable = true;
compilerParams.GenerateInMemory = true;


// Here comes the actual compilation , you pass in the actually source code here
System.CodeDom.Compiler.CompilerResults compilerRes = cSharpCompiler.CompileAssemblyFromSource(compilerParams, CodeSegment);

Now isnt that coool ???