Skip to content

Instantly share code, notes, and snippets.



Last active Feb 2, 2019
What would you like to do?
Scripting: `eval()`-like for C# using Roslyn and ScriptCS
  • Install Chocolatey
  • Reopen console application (for example cmd.exe) to update %PATH% and other environment variables
  • Install ScriptCs using chocolatey
  • Save both Roslyn-EvalSample.csx and packages.config
  • Install dependencies using scriptcs -install
  • Run scriptcs .\Roslyn-EvalSample.csx
<?xml version="1.0" encoding="utf-8"?>
<package id="Roslyn" version="1.2.20906.2" targetFramework="net45" />
<package id="Roslyn.Compilers" version="1.2.20906.2" targetFramework="net45" />
<package id="Roslyn.Compilers.Common" version="1.2.20906.2" targetFramework="net45" />
<package id="Roslyn.Compilers.CSharp" version="1.2.20906.2" targetFramework="net45" />
<package id="Roslyn.Services.Common" version="1.2.20906.2" targetFramework="net45" />
<package id="Roslyn.Services.CSharp" version="1.2.20906.2" targetFramework="net45" />
// Steps:
// * Get NuGet packages: `scriptcs -install`
// * Run scriptcs: `scriptcs .\Roslyn-EvalSample.csx`
using System;
using Roslyn.Services.Interactive;
using Roslyn.Scripting;
using Roslyn.Scripting.CSharp;
// limitations of scripts:
// * no `dynamic` keyword allowed
// * no async/await allowed
System.Console.WriteLine("Enter two commands to execute");
System.Console.WriteLine("For example:");
System.Console.WriteLine("var x = 6;");
System.Console.WriteLine("System.Math.Sqrt(x * 7)");
var scripts = new []
System.Console.ReadLine(), //fromValue:
System.Console.ReadLine() //formula:
var engine = new ScriptEngine(); // create script engine
Array.ForEach( // add references to assembiles
new[] { typeof(object).Assembly, GetType().Assembly },
@assembly => engine.AddReference(@assembly));
Array.ForEach( // import namespaces
new[] { "System" },
@namespace => engine.ImportNamespace(@namespace));
var session = engine.CreateSession();// create session
object resultModel = null;
// INFO: scripts are using same session
foreach(var script in scripts)
resultModel = session // process scripts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment