Windows Forms: Dynamically compile C# code at Runtime

How to Compile and Use C# code during Runtime (Dynamic compile C#)

Compiling and using C# code at runtime in a Windows Forms application can be achieved using reflection and the C# compiler service. Here's a basic outline of how you can accomplish this:

Open your Visual Studio, then click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "DynamicCompile" and then click OK

Drag and drop TextBox, Button controls from the Visual Studio toolbox onto your form designer, then design your form as shown below.

c# dynamic compile code

To compile C# code dynamically during runtime you can use the CSharpCodeProvider class in the System.CodeDom.Compiler namespace.

Add a click event handler to the Compile button as shown below.

//Compile code
private void btnCompile_Click(object sender, EventArgs e)
{
    // clear textbox, It's a TextBox control where user enters C# code
    txtStatus.Clear();
    // Compile the code
    CSharpCodeProvider csc = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", txtFramework.Text } });
    // Set up the compiler parameters
    CompilerParameters parameters = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll" }, txtOutput.Text, true);
    parameters.GenerateExecutable = true;
    CompilerResults results = csc.CompileAssemblyFromSource(parameters, txtSource.Text);
    if (results.Errors.HasErrors)
        results.Errors.Cast<CompilerError>().ToList().ForEach(error => txtStatus.Text += error.ErrorText + "\r\n");
    else
    {
        //Start your application
        txtStatus.Text = "----Build succeeded----";
        Process.Start(Application.StartupPath + "/" + txtOutput.Text);
    }
}

VIDEO TUTORIAL

Related