Let’s do scripting a bit

To able to use scripting API in .NET, Microsoft.CodeAnalysis.CSharp.Scripting package must install on your project.

dotnet add package Microsoft.CodeAnalysis.CSharp.Scripting

The API itself is well designed, and it’s easy to use, and it almost covers most of the scenarios from adding a reference, compiling to evaluating a simple code. You can access the CSharpScript class in Micorosft.CodeAnalysis.CSharp.Scripting .

In the following code, it reads whatever user types in console input and executes it immediately and return the result.

// Nampespace below should be used to use CSharpScript

// using Microsoft.CodeAnalysis.CSharp.Scripting; while(true)

{

var codeToEval = Console.ReadLine();

var result = await CSharpScript.EvaluateAsync(codeToEval);

Console.WriteLine(result);

}

Running of the example code

The CsharpScript.EvaluateAsync method is an async method for evaluating the string code. If you prefer strongly-typed eval, you can use the generic method of it.

int sum = await CsharpScript.EvaluateAsync<int>("1 + 2");

Adding namespaces

As you see in the example above, I used full qualification to use methods like System.DateTime . You can do it by using ScriptOptions parameter in the EvaluateAsync method.

while(true)

{

var codeToEval = Console.ReadLine(); var result = await CSharpScript.EvaluateAsync(codeToEval, ScriptOptions.Default.WithImports("System"));



Console.WriteLine(result);

}

The ScriptOptions.Default.WithImports("System") adds using System; to the script.

Now you can see, I evaluated the code without qualification.

Adding members of a type to the script

You all worked with System.Math class. Some times you prefer to add class members to the script to use directly without calling their class name. E.g., instead of System.Math.Abs just saying Abs . Like the adding references, if you use WithImports with a class name, it adds using static System.Math; .

while(true)

{

var codeToEval = Console.ReadLine(); var result = await CSharpScript.EvaluateAsync(codeToEval, ScriptOptions.Default.WithImports("System.Math"));



Console.WriteLine(result);

}

Adding References

Adding references is also easy with WithReferences method.