Windows Forms: Dynamically compile C# code at Runtime

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

Step 1Click 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

dynamic compile c#Step 2: Design your form as below

c# dynamic compile code

Step 3: Add code to handle your form as below

using Microsoft.CSharp;
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DynamicCompile
    public partial class Form1 : Form
        public Form1()

        //Compile code
        private void btnCompile_Click(object sender, EventArgs e)
            CSharpCodeProvider csc = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", txtFramework.Text } });
            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");
                //Start your application
                txtStatus.Text = "----Build succeeded----";
                Process.Start(Application.StartupPath + "/" + txtOutput.Text);