The Scripting API is finally here! After being removed from Roslyn’s 1.0 release it’s now available (for C#) in pre-release format on NuGet. To install to your project just run:
Install-Package Microsoft.CodeAnalysis.Scripting -Pre
Note: You need to target .NET 4.6 or you’ll get the following exception when running your scripts:
Could not load file or assembly 'System.Runtime, Version=18.104.22.168, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.
Note: Today (October 15, 2015) the Scripting APIs depend on the
1.1.0-beta1 release, so you’ll have to update your
Microsoft.CodeAnalysis references to match if you want to use all of Roslyn with the scripting stuff.
There are a few different ways to use the Scripting API.
CSharpScript.EvaluateAsync is probably the simplest way to get started evaluating expressions. Simple pass any expression that would return a single result to this method it will be evaluated for you.
Not every script returns a single value. For more complex scripts we may want to keep track of state or inspect different variables.
CSharpScript.RunAsync creates and returns a
ScriptState object that allows us to do exactly this. Take a look:
We can also maintain the state of our script and continue applying changes to it with
We can start to get into more interesting code by adding references to DLLs that we’d like to use. We use
ScriptOptions to provide out script with the proper
This stuff is surprisingly broad. The
Microsoft.CodeAnalysis.Scripting namespace is full of public types that I’m not at all familiar with and there’s a lot left to learn. I’m excited to see what people will build with this and how they might be able to incorporate scripting into their applications.
Kasey Uhlenhuth from the Roslyn team has compiled a list of code snippets to help get you off the ground with the Scripting API. Check them out on GitHub!
If you’ve got some cool plans for the scripting API, let me know if the comments below!