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.
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 method. For example, to get an integer value from a numeric expression, run the following:
int result = scriptEngine.Execute<int>("20+22");
#api #csharp #roslyn scripting api