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.
Â
Â
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:
Â
Â
Â
Â
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.
Â
Â
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:
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.
Â
Â
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.
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(); } } } }
Â
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()); } } } } }
Â
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."); } } } } }
Â
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."); } } } }
Â
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}"); } } } }
Â
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}"); } } } } }
Â
Â
The library is an especially good fit if:
Â
Â
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.