C# > Compiler and Runtime > C# Compilation Process > Dynamic Compilation with Roslyn

Simplified Scripting with Roslyn

This example demonstrates a simpler approach to dynamic code execution using Roslyn's scripting API. It's ideal for simple expressions or small snippets of code.

Prerequisites

Make sure you have the Microsoft.CodeAnalysis.CSharp.Scripting NuGet package installed.

Complete Code Example

This code uses CSharpScript.EvaluateAsync to execute a simple C# expression. It also includes error handling for compilation errors. The second part also includes the use of a variable in the script.

using Microsoft.CodeAnalysis.CSharp.Scripting;
using System;
using System.Threading.Tasks;

public class RoslynScripting
{
    public static async Task Main(string[] args)
    {
        string scriptCode = "Math.Pow(2, 10)";

        try
        {
            object result = await CSharpScript.EvaluateAsync(scriptCode);
            Console.WriteLine($"Result of script: {result}");
        }
        catch (CompilationErrorException e)
        {
            Console.WriteLine("Error compiling script:");
            foreach (var diagnostic in e.Diagnostics)
            {
                Console.WriteLine(diagnostic.ToString());
            }
        }

        //Example with variable
        string scriptCode2 = "var x = 10; x * 2";

        try
        {
            object result = await CSharpScript.EvaluateAsync(scriptCode2);
            Console.WriteLine($"Result of script: {result}");
        }
        catch (CompilationErrorException e)
        {
            Console.WriteLine("Error compiling script:");
            foreach (var diagnostic in e.Diagnostics)
            {
                Console.WriteLine(diagnostic.ToString());
            }
        }
    }
}

Step-by-Step Explanation

The code defines a C# expression as a string. Then, it uses CSharpScript.EvaluateAsync to compile and execute the expression. The result of the expression is then printed to the console. The try-catch block handles any compilation errors that may occur. The example demonstrates how to evaluate simple mathematical expressions and even include variables in the script.

Concepts Behind the Snippet

This snippet demonstrates the following concepts:

  • CSharpScript.EvaluateAsync: Compiles and executes a C# script.
  • CompilationErrorException: An exception thrown when the script fails to compile.

Real-Life Use Case

This approach is suitable for scenarios where you need to execute simple C# expressions, such as:

  • Calculators: Evaluating user-entered mathematical expressions.
  • Rule Engines: Executing simple business rules.
  • Data Transformation: Performing simple data transformations.

When to use them

Use this simplified scripting approach when:

  • You need to evaluate simple C# expressions.
  • You want a quick and easy way to execute dynamic code.
  • You don't need the full power of the Roslyn compiler API.

FAQ

  • What is the difference between CSharpScript.EvaluateAsync and the full Roslyn compiler API?

    CSharpScript.EvaluateAsync provides a simpler and more convenient way to execute simple C# expressions. The full Roslyn compiler API provides more control and flexibility, but it is also more complex to use.
  • How can I pass variables to the script?

    You can define variables within the script code itself, as demonstrated in the second example. Alternatively, you can pass variables to the script using the ScriptOptions object.