NativeAOT in .NET: How to Execute Dynamic C# Scripts Without JIT and Reflection.Emit

2026-11-25

NativeAOT in .NET: Running Dynamic C# Scripts Without JIT and Reflection.Emit

With every .NET release, NativeAOT keeps maturing and stops being exotic: applications are built into self-contained native binaries with instant startup, predictable memory consumption, and zero dependency on an installed runtime. But this medal has a flip side: together with the JIT compiler, the runtime also loses the ability to generate code while the program is running.

Yet this is exactly what the scripts embedded in enterprise systems are built for: discount formulas, user-editable validation rules, changeable business logic. The classic tools — Roslyn C# Scripting and System.Reflection.Emit — simply do not work in a NativeAOT application.

In this article, we will break down how AOT compilation works in .NET, why dynamic code generation is forbidden there, and how the FastScript .NET library, weighing about 300 KB, brings dynamic C# scripts back to life in a NativeAOT application. We will walk through six practical examples: from top-level code execution to sandboxing and protecting types from the trimmer.

 


 

1. What Is NativeAOT: AOT Compilation Instead of JIT

Typically, .NET applications are compiled into intermediate bytecode (IL). At startup, the virtual machine (CLR), with the help of the JIT compiler (Just-In-Time), translates this bytecode into machine instructions for the specific processor — on the fly. Flexible, but at the cost of a “warm-up” and considerable memory consumption by the compiler and metadata.

NativeAOT (Ahead-Of-Time) flips the process around: all source code is compiled into a platform-specific native binary at project build time. The final executable includes only the methods actually used and a minimal runtime, while the JIT compiler is eliminated entirely.

What this gives you in practice:

  • Instant startup. No JIT warm-up is needed — execution begins in milliseconds.
  • Low RAM consumption. The absence of bulky metadata and the compiler in memory saves tens and hundreds of megabytes.
  • Self-containment. The outcome is a compact single binary: there is no need to deploy the .NET Runtime on a server or client machine.

 


 

2. Where NativeAOT Truly Shines

  • Console CLI utilities. Command-line utilities open instantly and compete with C++ and Rust programs in startup speed.
  • Microservices and containers (Docker, Kubernetes). Reduced memory consumption lets you run noticeably more service replicas on a single physical server.
  • Environments with strict security policies (iOS, WebAssembly). In these environments, allocating memory for executable code while the program is running is forbidden at the OS level.

 


 

3. The Problem: Dynamic Code Is Incompatible with AOT

Many enterprise systems need flexibility: discount calculations using formulas from a database, custom validations, execution of user scenarios. The classic solution is Roslyn C# Scripting or System.Reflection.Emit.

However, in NativeAOT, any attempt to compile or load a new assembly at runtime is guaranteed to result in a critical failure. There are two reasons: first, the runtime has no JIT compiler that could turn IL into machine code; second, the trimmer removes everything that is not statically referenced at build time — which means even a correctly loaded assembly will lose the required methods and types.

In other words, the familiar model of “compile code at runtime — then execute” simply does not exist in the AOT world. A fundamentally different execution mechanism is needed.

 


 

4. The Solution: FastScript.NET — a C# Interpreter for NativeAOT

To solve this problem, FastScript.NET was created — a lightweight cross-platform library of about 300 KB for directly executing C# scripts without compiling them into machine code.

FastScript.NET follows the classic pipeline:

  • Lexer splits the script text into a stream of tokens.
  • Parser builds an abstract syntax tree (AST) from the tokens.
  • Interpreter walks the AST nodes step by step and executes commands on the fly.

Since the library generates nothing at the machine-code level, it is fully compatible with NativeAOT: it causes no trimmer warnings and runs safely on iOS and WebAssembly.

 


 

5. Practical Examples: Six Integration Scenarios

Let us look at the key scenarios for integrating FastScript.NET into C# applications — from running a simple script to sandboxing and interacting with the NativeAOT trimmer.

Example 1. Executing Top-Level Code (RunMain)

The main class for working with scripts is CSharpScript (the FastScript.CSharp namespace). The simplest scenario is parsing and running top-level statements:

using FastScript;
using FastScript.CSharp;
using FastScript.Runtime.Types;
 
namespace FastScriptDemo
{
    class Program
    {
        static void Main()
        {
            var text = @"
using System;
Console.WriteLine(""Hello!"");
";
 
            var script = new CSharpScript();
            if (script.Compile(text))
            {
                script.RunMain();
            }
        }
    }
}

 

Example 2. Diagnostics and Handling Syntax Errors (Diagnostic.Errors)

If the script contains errors, the Compile() method returns false. Detailed information — with line numbers, columns, and code fragments — is available through Diagnostic.Errors:

using FastScript;
using FastScript.CSharp;
using FastScript.Runtime.Types;
 
namespace FastScriptDemo
{
    class Program
    {
        static void Main()
        {
            string invalidScript = @"
using System;
int x = 10
Console.WriteLine(x.NonExistingMethod());
";
 
            var script = new CSharpScript();
            if (!script.Compile(invalidScript))
            {
                Console.WriteLine("Syntax errors found in the script:");
                foreach (var err in script.Diagnostic.Errors)
                {
                    Console.WriteLine($"{err.CompilationUnit.Name} ({err.Line}, {err.Column}): error {err.Code}: {err.Message}");
                    Console.WriteLine(err.SourceCode());
                }
            }
        }
    }
}

 

Example 3. Instantiating Classes from a Script and Invoking Methods (ScriptTypeInfo)

If the script declares business logic classes, the host application can instantiate them and call their methods:

using FastScript;
using FastScript.CSharp;
using FastScript.Runtime.Types;
 
namespace FastScriptDemo
{
    class Program
    {
        static void Main()
        {
            string code = @"
public class Calculator
{
    public decimal GetDiscount(decimal total)
    {
        return total > 10000 ? total * 0.15m : total * 0.05m;
    }
}
";
 
            var script = new CSharpScript();
            if (script.Compile(code))
            {
                // Look up by the class short name: "Calculator"
                var calcType = script.Types["Calculator"] as ScriptTypeInfo;
                if (calcType != null)
                {
                    var instance = calcType.CreateInstance();
                    var method = calcType.GetMethod("GetDiscount");
                    object discount = method.Invoke(instance, new object[] { 15000m });
                    Console.WriteLine($"[Script] Discount on $15,000: {discount} USD.");
                }
                else
                {
                    Console.WriteLine("Type Calculator not found in the script.");
                }
            }
        }
    }
}

 

Example 4. A Safe Sandbox: Restricting the API (TypeProvider)

For user-provided scripts, you can restrict access to potentially dangerous namespaces — for example, file system or network operations:

using FastScript;
using FastScript.CSharp;
using FastScript.Runtime.Types;
 
namespace FastScriptDemo
{
    class Program
    {
        static void Main()
        {
            var script = new CSharpScript();
 
            // Restrict the list of allowed assemblies and block namespaces
            script.TypeProvider.IncludeAssemblies = new[] { "System.Private.CoreLib", "System.Console" };
            script.TypeProvider.ExcludeNamespaces = new[] { "System.IO", "System.Net" };
 
            string maliciousScript = @"
using System.IO;
File.Delete(""important.db""); // Will cause a parse error
";
 
            if (!script.Compile(maliciousScript))
            {
                Console.WriteLine("The script was blocked by the security policy.");
            }
        }
    }
}

 

Example 5. Modular Script Structure (CompilationUnit)

Scripts can be logically split into several independent files and modules:

using FastScript;
using FastScript.CSharp;
using FastScript.Runtime.Types;
 
namespace FastScriptDemo
{
    class Program
    {
        static void Main()
        {
            var unit1 = new CompilationUnit("Utils.cs", @"
public static class MathUtils
{
    public static int DoubleValue(int val)
    {
        return val * 2;
    }
}
");
 
            var unit2 = new CompilationUnit("Main.cs", @"
using System;
public class App
{
    public static void Main()
    {
        int res = MathUtils.DoubleValue(7);
        Console.WriteLine(""[Script] Doubled value of 7: "" + res);
    }
}
");
 
            var script = new CSharpScript();
            if (script.Compile(unit1, unit2))
            {
                script.RunMain();
            }
            else
            {
                foreach (var err in script.Diagnostic.Errors)
                    Console.WriteLine($"Module error: {err.Message}");
            }
        }
    }
}

 

Example 6. NativeAOT Specifics: Preserving Types from the Trimmer (DynamicDependency)

When building with NativeAOT, the trimmer removes all code that is not used statically. So that the script can dynamically call host application types, protect them with the [DynamicDependency] attribute:

using FastScript.CSharp;
using FastScript.Runtime.Types;
 
namespace FastScriptNativeAotTrimDemo
{
    internal class Program
    {
        static void Main(string[] args)
        {
            AppHost.EnsureAOTTypes();
            AppHost.RunScript();
 
            Console.WriteLine("\nPress Enter to exit...");
            Console.ReadLine();
        }
    }
 
    public class AppHost
    {
        [DynamicDependency(DynamicallyAccessedMemberTypes.All, typeof(List<>))]
        [DynamicDependency(DynamicallyAccessedMemberTypes.All, typeof(Console))]
        public static void EnsureAOTTypes()
        {
            var list = new List<string>();
            list.Add("keep");
            _ = list.Count;
            _ = list[0];
            Console.WriteLine();
        }
 
        public static void RunScript()
        {
            Console.WriteLine("[1/3] Preparing a C# script that uses List<string>...");
 
            string scriptText = @"
using System;
using System.Collections.Generic;
 
public class ScriptRunner
{
    public static void Main()
    {
        List<string> list = new List<string>();
        list.Add(""Item 1: Safe for NativeAOT"");
        list.Add(""Item 2: The trimmer kept List<string>"");
        list.Add(""Item 3: Executed via FastScript.NET"");
 
        for (int i = 0; i < 3; i++)
        {
            Console.WriteLine("" [Script] "" + list[i]);
        }
    }
}
";
 
            var script = new CSharpScript();
 
            Console.WriteLine("[2/3] Compiling the script into an AST tree...");
            if (script.Compile(scriptText))
            {
                Console.WriteLine("[3/3] Executing the ScriptRunner.Main() method...");
                script.RunMain();
                Console.WriteLine("[Success] The script correctly accessed List<string> methods in the compiled binary!");
            }
            else
            {
                Console.WriteLine("[Error] Failed to compile the script:");
                foreach (var err in script.Diagnostic.Errors)
                {
                    Console.WriteLine($" -> [Error {err.Code}] Line {err.Line}, column {err.Column}: {err.Message}");
                }
            }
        }
    }
}

 


 

6. When FastScript.NET Is a Good Choice

The library is an especially good fit if:

  • the application is built with NativeAOT, and business logic must change without rebuilding and redeploying the binary;
  • user scenarios need isolation: an assembly whitelist and blocking of dangerous namespaces handle this at the parsing stage;
  • predictable memory consumption and the absence of the warm-up required by Roslyn scripting matter;
  • the target platforms are iOS, WebAssembly, or containers with strict memory limits.

 


 

Conclusion

NativeAOT sets new rules for the .NET ecosystem: instant startup, a compact binary, and minimal memory consumption — in exchange for a complete rejection of dynamic compilation. Roslyn and Reflection.Emit do not work in this world, which means the classic scripting mechanisms lose their power.

FastScript.NET closes this gap architecturally rather than with a “workaround”: an interpreter that executes scripts over the AST requires neither JIT nor assembly generation. As a result, the balance between the performance of the compiled binary and the flexibility of dynamic business logic is preserved — discount formulas, validations, and user scenarios can be changed without rebuilding the application.

If your project is moving toward AOT compilation while scripts still live inside it — now is the time to take a closer look at the interpreted approach.

.NET FastReport Script NativeAOT
November 10, 2026

How to add your own component to FastReport Online Designer

Learn how to add a custom component to FastReport Online Designer: build a JS plugin with a preview and settings dialog, then connect the server-side .NET class.
October 26, 2026

TfrImageComboBox: A drop-down list with images and text captions in FastReport VCL

TfrImageComboBox from FastEditors VCL: a drop-down list with icons and labels for FastReport VCL. Properties, events, and usage examples in Delphi.
October 26, 2026

Progress Bar in Delphi: The TfrProgressBar and TfrxProgressBar Components from FastReport VCL

Let’s take a closer look at the TfrProgressBar and TfrxProgressBar components from FastReport VCL: configuring the progress scale, thresholds and markers, binding to data, and a Delphi example.

© 1998-2026 Fast Reports Inc.