C# code execution at runtime with the Microsoft Roslyn CSharp ScriptEngine class

Microsoft has released the Roslyn CTP which allows developers to use the Visual Basic and C# compilers as APIs. The snippet below can be used to execute C# code at runtime.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Roslyn.Scripting.CSharp;
using Roslyn.Compilers.CSharp;
using Roslyn.Compilers;
using System.Diagnostics;
using System.IO;

namespace ExpressionExecution
{
    public partial class ExpressionEditor : Form
    {
        public ExpressionEditor()
        {
            InitializeComponent();
        }

        private void buttonRun_Click(object sender, EventArgs e)
        {
            ScriptEngine scriptEngine = new ScriptEngine();

            try
            {
                object result = scriptEngine.Execute(textBoxSource.Text);
                textBoxOutput.Text = result + "";
            }
            catch (Exception ex)
            {
                textBoxOutput.Text = ex.Message;
            }

        }
    }
}

Output:

C# code execution at runtime

 

 

 

 

This entry was posted in C# and tagged , , , , , , , . Bookmark the permalink. Trackbacks are closed, but you can post a comment.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Why ask?