C# Corner

Using The Roslyn Scripting API in C#

Learn how to utilize the Roslyn Scripting API to host a C# scripting engine in your applications.

I first learned about the C# compiler as a service workings way back in 2008 at PDC. At that time, Anders Hejlsberg gave a brief preview of what was to come by showing off a C# Read-Evaluate-Print-Loop (REPL) demo. Since then the project has progressed to include powerful code analysis and compiler APIs as well. In this column I'll  demonstrate how to utilize the C# Roslyn Scripting API to execute expressions , code blocks and classes from a string or file.

Getting Started

The first step is to procure and install the Roslyn CTP bits from bit.ly/rThx5k. Once Roslyn is set up, open up Visual Studio and you should see the Roslyn templates available for both C# and VB.NET, as shown in Figure 1.


[Click on image for larger view.]
Figure 1. Roslyn Visual Studio Templates.

Figure 1: Roslyn Visual Studio Templates

Next create a new Console Application, open up Program.cs and add the following using statements.

using Roslyn.Scripting;
using Roslyn.Scripting.CSharp;

You're now set up to run any of the code examples in the remainder of the article.

Executing a C# Expression

One of the most basic scripting needs is the ability to execute a given expression. Accomplishing this task with Roslyn is very similar to using the Dynamic Language Runtime (DLR) . First create a  ScriptEngine instance for your target language, in this case C#:

 ScriptEngine  scriptEngine = new ScriptEngine();

Then use the Execute method to run the given expression:

 scriptEngine.Execute("1+1");

The expression above would return an object with a value of 2.

If you know the return type, you can also use the generic Execute<T> method. For example, to get an integer value from a numeric expression, run the following:

 int result =  scriptEngine.Execute<int>("20+22");

Executing a Code Block and Classes

The Execute method can also be used to execute code blocks, including control statements and even an entire class. To execute a foreach script block to increment each item in a collection, for example, you would call:

scriptEngine.Execute("foreach(int  item in numbers) { item += 1;    };");

To execute an entire class, you can simply pass it to the Execute method. For example, to execute a custom class named DemoClass that contains one method named Test you would run:

scriptEngine.Execute("Public  class DemoClass() {" +
"public string Test { return "Test Method"; } +
"}"

Maintaining an Execution Context

The Execute method contains an overloaded signature for passing a Session object. The Session object is used for maintaining an execution context. To create a context, use the Session.Create() method:

 Session  mySession = Session.Create();

After a session's been created, pass it to the ScriptEngine Execute method whenever you call it. For example, you can create a variable in one Execute invocation and then access it in a succeeding Execute invocation:

scriptEngine.Execute("int number = 40;", mySession);
scriptEngine.Execute("number += 2;", mySession);

Executing a File

The SciptEngine  also allows for execution of a given C# code file. You can execute either a standard  .cs C# file or a .csx C# script with the ScriptEngine's ExecuteFile method. To execute a standard C# file, run the following:

 scriptEngine.ExecuteFile("DemoClass.cs");
Running a C# script file is just as easy:
scriptEngine.ExecuteFile("DemoScript.csx");

Creating a Read Evaluate Print Loop (REPL)

This is just the tip of the iceberg; with a little work, you can create a REPL quite easily. For the sake of clarity and clean code, I'll encapsulate the Scripting API access into a new class named ScriptHost. The ScriptHost class exposes the Execute, Execute<T>, and ExecuteFile methods of the Roslyn C# ScriptEngine.

In addition, I used an overloaded ScriptEngine constructor to pass in the assemblies and namespaces that will be available to the consumer of the ScriptHost. The ExecuteFile method is not used in the demo application, but could come in quite handy for loading utility classes for use by the scripting engine. See Listing 1 for the full contents of the ScriptHost class.

In the console application, I make use of the ScriptHost class to execute the user's given C# expressions in a loop. If the user enters the word "quit", the program silently exits.  I opted to catch any Exceptions that might occur and display them to the user. See Listing 2 for the full REPL application code, and Figure 2 for the resulting output.


[Click on image for larger view.]
Figure 2. C# REPL in action.

Looking Forward

The Roslyn project is looking very promising, and already has a lot of powerful APIs available for developers to wield. Today I've shown only the Scripting API, which can be used to host C# or VB.NET in a .NET application. Stay tuned for the next installment, covering how to use the Compiler APIs to analyze C# syntax and semantics and compile code.

About the Author

Eric Vogel is a Senior Software Developer for Red Cedar Solutions Group in Okemos, Michigan. He is the president of the Greater Lansing User Group for .NET. Eric enjoys learning about software architecture and craftsmanship, and is always looking for ways to create more robust and testable applications. Contact him at [email protected].

comments powered by Disqus

Featured

  • Compare New GitHub Copilot Free Plan for Visual Studio/VS Code to Paid Plans

    The free plan restricts the number of completions, chat requests and access to AI models, being suitable for occasional users and small projects.

  • Diving Deep into .NET MAUI

    Ever since someone figured out that fiddling bits results in source code, developers have sought one codebase for all types of apps on all platforms, with Microsoft's latest attempt to further that effort being .NET MAUI.

  • Copilot AI Boosts Abound in New VS Code v1.96

    Microsoft improved on its new "Copilot Edit" functionality in the latest release of Visual Studio Code, v1.96, its open-source based code editor that has become the most popular in the world according to many surveys.

  • AdaBoost Regression Using C#

    Dr. James McCaffrey from Microsoft Research presents a complete end-to-end demonstration of the AdaBoost.R2 algorithm for regression problems (where the goal is to predict a single numeric value). The implementation follows the original source research paper closely, so you can use it as a guide for customization for specific scenarios.

  • Versioning and Documenting ASP.NET Core Services

    Building an API with ASP.NET Core is only half the job. If your API is going to live more than one release cycle, you're going to need to version it. If you have other people building clients for it, you're going to need to document it.

Subscribe on YouTube