On The Fly Code Compilation & Execution in C#

I have moved to a different position since last one month and I get to do some R&D and I am trying to coming up with tools which can help Developers to finish their tasks as soon as possible without facing any road blocks.

I was trying to figure out a way to compile and execute code on the fly without storing the output to disk, and after looking at some examples on MSDN I came up with this code.

namespace CrmXpress.CodeDom

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.Reflection;

public partial class CodeDomForm : Form
public CodeDomForm()

private void AddButton_Click(object sender, EventArgs e)
CSharpCodeProvider provider = new CSharpCodeProvider();
ICodeCompiler ICC = provider.CreateCompiler();

// You have to add all the valid references here i.e. all the assemblies which you are going to use in your code
var parameters = new CompilerParameters(new[] { “System.Windows.Forms.dll” });

// Generate the assembly in memory
parameters.GenerateInMemory = true;

// This is a class stub
  string code = “namespace Skynet{class XXX{public void Execute(){{0}}}}”;

// Replace the placeholder with actual code that you have written in CodeTextBox
code = code.Replace(“{0}”, this.CodeTextBox.Text);

// Compile the code
CompilerResults result = ICC.CompileAssemblyFromSource(parameters, code);

// If there are any errors, display a message to end user
if (result.Errors.Count > 0)
// Otherwise using reflection, create instance of XXX class in memory and call the Execute method
Assembly assmebly = result.CompiledAssembly;
  object target = assmebly.CreateInstance(“Skynet.XXX”);
target.GetType().InvokeMember(“Execute”, BindingFlags.InvokeMethod, null, target, null);

// you can use this sample code to run minor test. If you copy this code right, on click of Add button you should see : “GFYS : 11”.
/*int x = 5;
int y = 6;
System.Windows.Forms.MessageBox.Show(“GFYS : ” + (x + y));*/



Comments/Questions are welcome.

Leave a Reply

Your email address will not be published. Required fields are marked *