Hacking C# type constraints and boxing with IL and manual stack placement
A Zenn article describes an experiment into calling Dispose on generics without type constraints and without heap allocations, in .NET and Unity. Writing IL by hand with InlineIL.Fody, the author removes the "where T : IDisposable" constraint and emits ldarg, "constrained. !!T", callvirt Dispose — this works on .NET 10/11 RC CoreCLR, Native AOT, and all tested Unity backends, mutating the original variable (Counter.Count going from 41 to 42). To avoid passing non-disposable types like int, a TryDispose method caches per-T checks of IDisposable implementability. Tests of passing unconstrained T into constraint-bearing methods show VerificationException on CoreCLR where Mono and IL2CPP succeed, and Reflection-based invocation was mostly rejected with ArgumentException except on IL2CPP.
The second part avoids boxing for interface casts. A plain cast from a ref T to IDisposable measured 0 B per call because the JIT can eliminate the box when the call target is known, while the pattern-matching form "if (value is IDisposable disposable)" costs 24 B per call and keeps the allocation when changes must be written back. The author then builds a StackBox<T> struct with two IntPtr prefix words plus the value, writing the runtime-specific type word — MethodTable* for CoreCLR/Native AOT, MonoVTable* for Mono, Il2CppClass* for IL2CPP — into the header and treating the address as an object reference, magic that raw memory layout work makes possible. Type information is obtained via TypeHandle on CoreCLR/Native AOT, mono_class_from_mono_type and mono_class_vtable via P/Invoke on Mono, and il2cpp_class_from_type on IL2CPP.
Caveats are stated explicitly: passing int directly crashes (EntryPointNotFoundException or process exit code 0xC0000602 on Native AOT), interface default implementations that store "this" would hold a reference that dangles once the stack frame exits, and the author does not recommend the manual stack-boxing technique for practical use. The experiment code and reproduction steps are in the csharp-boxing-research repository on GitHub, tested on Windows x64 with Unity 6.3 and Unity 7 alpha.
Sources
-
JPZenn JA
【.NET/Unity】C# の型制約とボックス化をハックする — IL と手動スタック配置
Terms
- constrained. — An IL prefix instruction that calls an interface method on a type parameter without boxing when the type itself implements the method.
- InlineIL.Fody — A build-time tool based on Fody that lets you write raw IL instructions directly inside C# methods.
- IL2CPP — Unity's backend that converts IL into C++ source and compiles it to native code, using its own object layout.
- TypeHandle — A runtime handle that points to the internal type information structures (MethodTable, MonoType, Il2CppType) describing a type.


