EmitToolbox 0.3.1

dotnet add package EmitToolbox --version 0.3.1
                    
NuGet\Install-Package EmitToolbox -Version 0.3.1
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="EmitToolbox" Version="0.3.1" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="EmitToolbox" Version="0.3.1" />
                    
Directory.Packages.props
<PackageReference Include="EmitToolbox" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add EmitToolbox --version 0.3.1
                    
#r "nuget: EmitToolbox, 0.3.1"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package EmitToolbox@0.3.1
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=EmitToolbox&version=0.3.1
                    
Install as a Cake Addin
#tool nuget:?package=EmitToolbox&version=0.3.1
                    
Install as a Cake Tool

EmitToolbox

Using System.Reflection.Emit to dynamically create types and methods at runtime is prone to errors and can be quite complex. To effectively emit dynamic IL code, one must have a deep understanding of the Common Intermediate Language (CIL) and the .NET runtime. The EmitToolbox library aims to simplify this process by providing a set of high-level abstractions and utilities.

Concepts

  • 'DynamicAssembly': Builder for defining dynamic assemblies. It can define classes and structs.
  • 'DynamicType': Builder for defining dynamic types. Use it to create DynamicMethod, DynamicField and DynamicProperty instances.
  • 'DynamicFunction': Builder for defining the code of dynamic methods. This framework provides rick extension methods to it.
  • 'DynamicField': Builder for defining dynamic fields.
  • 'DynamicProperty': Builder for defining dynamic properties and corresponding setters and getters.

Usage

Create a Dynamic Assembly

Use the following code to create an executable dynamic assembly:

var assembly = DynamicAssembly.DefineExecutable("SampleAssembly");

Or you can create an assembly that can be exported to a file but cannot be executed directly:

var assembly = DynamicAssembly.DefineExportable("SampleAssembly");

// ...

assemly.Export("./MyDynamicAssembly.dll");

Basic Example

using EmitToolbox.Framework;
using EmitToolbox.Framework.Extensions;
using EmitToolbox.Framework.Symbols;

var assembly = DynamicAssembly.DefineExecutable("SampleAssembly");
var type = assembly.DefineClass("SampleClass");

// Define an instance field named 'Backing' of type 'int'
var backingField = type.FieldFactory.DefineInstance(typeof(int), "Backing");
// Define an instance property named 'Value' of type 'int'
var valueProperty = type.PropertyFactory.DefineInstance<int>("Value");

// Define and bind getter accessor for the property
var getter = type.MethodFactory.Instance.DefineFunctor<int>(
    "get_Value", [], hasSpecialName: true);

// Get the 'this' instance symbol.
// This symbol is used to access the instance field in the method body.
var thisSymbol = getter.This();
// Convert the dynamic field into a symbol than can be used in the method building context
// by binding it to the 'getter' method and 'this' instance.
var fieldSymbol = backingField.SymbolOf<int>(getter, thisSymbol);

// Return the value of the field + 1.
// Here, extension operator '+' for 'ISymbol<int>' is used.
// Use the namespace 'EmitToolbox.Framework.Extensions' to access these extension methods.
// 'getter.Value(1)' is to create a literal symbol that represents the value 1.
getter.Return(fieldSymbol + getter.Value(1));

// Bind the 'getter' method as the getter accessor of this property.
valueProperty.BindGetter(getter);
// After building this type, the type and its methods, fields, and properties can be used.
type.Build();

// Following example is about to use this type throw reflection.
// Usually, the built types implement interfaces, and they should be used as interfaces for better performance.
// This part is only for demonstration purpose.

// Instantiate an instance of the built type.
var instance = Activator.CreateInstance(type.BuildingType)!;
// Create a functor from the getter accessor of the property.
var functor = valueProperty.Getter!.BuildingMethod.CreateDelegate<Func<int>>(testInstance);

// Using reflection to set the value of the backing field to 1.
backingField.BuildingField.SetValue(instance, 1);
// Then invoke the functor, the result should be 3.
var result = functor(2);

Define an Async Method

Suppose we have async methods like this:

public static Task<int> ReturnCompletedTask1()
{
    return Task.FromResult(1);
}

public static async Task<int> ReturnDelayedTask1()
{
    await Task.Delay(10);
    return 1;
}

And we want to define an async method that has the same behavior as the following code:

public async Task<int> DynamicMethod()
{
    return (await ReturnCompletedTask1()) + (await ReturnDelayedTask1());
}

var assembly = DynamicAssembly.DefineExecutable("SampleAssembly");
var type = assembly.DefineClass("SampleClass");

var method = type.MethodFactory.Static.DefineFunctor<Task<int>>(
    nameof("DynamicMethod"));

var asyncBuilder = method.DefineAsyncStateMachine();
// Note that the async part is defined in another method context.
// It is actually the 'MoveNext' method of the state machine.
var asyncMethod = asyncBuilder.Method;
// Define a new async step with 'AwaitResult' method, which can await task-like objects.
var symbolNumber1 = asyncBuilder.AwaitResult(
    asyncMethod.Invoke(() => ReturnCompletedValueTask1()));
// Note that the 'MoveNext' methods may be called multiple times for different steps;
// therefore, temporary variables will be lost and need to be retained.
// Results of the 'AwaitResult' are stored in fields of the state machine,
// and other variables need to be manually retained through the 'Retain(ISymbol)' method.
var symbolNumber2 = asyncBuilder.AwaitResult(
    asyncMethod.Invoke(() => ReturnDelayedValueTask1()));
var result = symbolNumber1 + symbolNumber2;
// Set the result value as the result of the task.
asyncBuilder.Complete(result);

// The method returns the task of the state machine.
method.Return(asyncBuilder.Invoke().AsSymbol<Task<int>>());

type.Build();

// Use the method:
var functor = method.BuildingMethod.CreateDelegate<Func<Task<int>>>();
var result = await functor(); // Result is 2.
Product Compatible and additional computed target framework versions.
.NET net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (1)

Showing the top 1 NuGet packages that depend on EmitToolbox:

Package Downloads
InjectionExpert

A dependency injection library based on dynamic IL generation. It supports constructor injection and member injection.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.3.1 187 12/23/2025
0.3.0 420 11/19/2025
0.2.3 330 8/25/2025
0.2.2 334 8/25/2025
0.2.1 298 8/25/2025
0.2.0 208 8/24/2025
0.1.1 198 8/14/2025

[Version 0.3.1]

This release introduces significant enhancements to the framework's capabilities and refines the core APIs for better semantic clarity.
The updates focus on expanding asynchronous programming support, improving the debugging experience, and hardening the type system.

New Features:
1) [Highlight] Add 'TaskStateMachineBuilder' to support building async methods;
   you can use 'DefineAsyncStateMachine()' method to define the async part of a method.
2) [Highlight] Add 'ToString()' to 'DynamicFunction' to help with debugging;
   it will print the IL code in human-readable format.
3) You can use 'MarkGotoOnlyScope' to define a scope that is executed only when it is reached by a goto instruction.
4) Add extension methods to create 'ValueTuple<...>' from value symbols.
5) 'AssignNew' now supports in-place construction with the 'inplace' option;
   it will try to construct the object on the specified memory address if possible.

Problem Fixes:
1) Literal value assignment now correctly supports booleans, strings, and null.
2) Fix the incorrect behavior of nullability check for 'Nullable<T>' symbols.
3) Fix the incorrect by-ref checking of the 'LoadAsTarget' method.

Other Changes:
1) Rename 'Initialize' to 'AssignNullOrDefault' to make them more semantically clear.
2) Rename 'Value' to 'Literal' to make them more semantically clear.
3) Now 'FieldSymbol' will check whether the instance is correctly provided according to whether the field is static;
   meanwhile, the 'instance' argument is not optional to reduce the chance of misuse.
4) 'InvocationOperation' now will check the length of arguments and parameters.

NOTE:

The Roslyn Compiler of .NET 10 has some issues causing it to generate false-positive warnings
about the nullability constraints of generic extension methods, such as CS8620.
This issue has been reported to Microsoft, and we are following up with updates.