Archive for November, 2010

C# Scripting


Adding scripting in a C# application is really easy.

In that post, I will show you how to incorporate C# into your C# program.

I have created a small Script class that allow you to define a function with parameters and a return type, provide code and execute it.


The code below define a new script that return the integer 3:

Script script = new Script("Test", "return 3;", typeof(int));
object ret = script.Execute();

The following example define a script taking a string as first argument and showing a MessageBox with a Hello :

string code = "MessageBox.Show(\"Hello \" + name);";
Script script = new Script("Test", code);
script.AddParameter("System.String", "name");
script.Execute(new object[] {"Test"});

See the generated code

You can also see the generated code with the GenerateCode method:

//     This code was generated by a tool.
//     Runtime Version:2.0.50727.4952
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
namespace ScripterNamespace10111921232181
    using System;
    using System.Collections.Generic;
    using System.Text;
    public sealed class ScripterClass
        public static object ScripterMethod()
            return 3;

Demo application

I have created a small application that allow you to enter code, compile, run it and see the output.

Categories: C#, Scripting