Skip to content

C# 7 support (hosted)

Oleg Shilo edited this page Jan 7, 2019 · 3 revisions

Note this page describes how to enable C# 7 support for hosted script execution.

Usage - CS-Script.Evaluator

If you want to use C#7 syntax in your scripts you can just add CS-Script.bin or CS-Script (comes with code samples) to your project and you are ready to go. Though you will be have to use Roslyn evaluator for all your scripts:

CSScript.EvaluatorConfig.Engine = EvaluatorEngine.Roslyn; 
...
var product = CSScript.Evaluator
                      .LoadDelegate<Func<int, int, int>>(
                                  @"int Product(int a, int b)
                                    {
                                        var result = a * b;
                                        Console.WriteLine($""result: {result}"");
                                        return result;
                                    }");
int result = product(3, 2);

Usage - CS-Script.Native

Though if you prefer to use either CS-Script.Native or CodeDom flavor of the evaluator (EvaluatorEngine.CodeDom) then you need add a special NuGet package (provided by Microsoft) to your project - "Microsoft.Net.Compilers".

Unfortunately Microsoft has stopped distributing its latest compilers with .NET and currently it is the only way they allow the latest compilers to be brought to the system.

To simplify this you can just add one "CS-Script.RoslynProvider" package, which brings all dependencies that you might need.

Depending on your VS settings it can add the package as project reference or as package.config.

In both cases NuGet does not copy the compilers in your build (Release/Debug) folder thus you need carefully instruct CS-Script where to find Roslyn compilers (C#7 compiler).

packages.config

If you add this package via "package.config" you can use the Roslyn setup routine from the sample "Scripting.native.Roslyn.cs" file distributed with the package. NuGet will add it to your project

PackageReference

If you add this package via PackageReference it will only add to your project assembly references but not the sample file. The code below shows how to integrate Roslyn with the script engine in this case:

static void SetupRoslyn()
{
    var localDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
 
    CSScript.GlobalSettings.UseAlternativeCompiler = Path.Combine(localDir, "CSSRoslynProvider.dll");
    CSScript.GlobalSettings.RoslynDir = Environment.ExpandEnvironmentVariables(@"%USERPROFILE%\.nuget\packages\Microsoft.Net.Compilers\2.2.0\tools");
}
 
static void Main(string[] args)
{
    SetupRoslyn();
 
    var sayHello = CSScript.LoadDelegate<Action<string>>(
                            @"void SayHello(string greeting)
                              {
                                  Console.WriteLine($""Gritting: {greeting}!"");
                              }");
 
    sayHello("Hello World!");
}