C# scripting!

After much struggle, learning and googling, I’ve finally made my own small library that provides a simple C# code editor and a bunch of simple C# scripting utilities.

A few years ago I wrote a simple Scintilla.net-based code editor and, with the Microsoft CSharp scripting library, managed to let my apps provide code editing and run-time C# script execution. The code was scrappy and without intellisense also difficult to use for non-trivial scripts.

Then I found the RoslynPad project, which uses AvalonEdit for the underlying text editor to provide a WPF C# scripting editor. As well as a stand-alone application the text editor is also available via NuGet. Since I work almost entirely with WinForms, rather than WPF, I wanted an easy-to-use drag-and-drop widget to provide code editing. So I wrote CDS.CSharpScripting.

As well as the code editor there are classes for script compilation and execution, including EasyScript, a class that allows for one-line compilation and execution. The compiler utilities provide access to the compilation results such as errors and warning.

Example 1:

EasyScript<object>.Go("Console.WriteLine(\"Hello world, from the script!\");");

Output:

Hello world, from the script!

There’s still lots to do on the project including mode demos, getting code actions to work – they actual actions do already work but the menu text is broken.

If you need something with more power than my simple code editor wrapper then the RoslynPad project is available on GitHub. There are also countless demos showing how to use Microsoft’s C# scripting classes directly. But if you just need a quick code editor and the ability to compile and run code at runtime, capture script return values and share data between the host app and the script, then this is not a bad place to start.

Happy scripting.

🙂