ADR 0019 — dynamic: bound at compile time, per run-time type, with Roslyn
- Status: Accepted (2026-10-30), implemented (
CodeGen/ModuleCodeGen.Dynamic*.cs,CodeGen/FunctionCodeGen.Dynamic.cs,CodeGen/DynamicSite.cs,CodeGen/DynamicErasure.cs,corelib/Dynamic/DynamicObjects.cs); from IL since 2026-10-31 (CodeGen/FunctionCodeGen.IlDynamic.cs,CodeGen/ModuleCodeGen.DynamicIl.cs,Frontend/DynamicBinding.Il.cs). - Context: ADR 0006 (closed world), ADR 0013 (framework IL), ADR 0016 (NativeAOT parity), ADR 0018 (reflection metadata).
Context
C# compiles a dynamic operation to a call site: CallSite<Func<...>>.Create(Binder.InvokeMember(flags, "Foo", typeArgs, typeof(Context), argumentInfos)), then site.Target(site, receiver, args...). On the first call (and for every new
combination of run-time types) Microsoft.CSharp’s runtime binder — a port of the C# compiler’s semantic analysis — binds the
operation “as if the user had written it” against the run-time types of the dynamic operands (the best accessible type:
the nearest type the calling context can see, TypeManager.GetBestAccessibleType), builds an expression tree for the rule,
and the DLR compiles it into the site’s delegate. Under NativeAOT the binder runs on reflection metadata and the rule
delegates are interpreted (System.Linq.Expressions’ LightCompiler).
What NativeAOT does is a weak target. The corpus program that measured parity (using-dynamic) works under NativeAOT
because it only produces a binder error; a dynamic call to a method nothing else references fails with “‘Point’ does not
contain a definition for ‘Add’” (the trimmer removed it), and with [DynamicDependency] keeping it the binder fails with an
ArgumentNullException. built-in-types (value.GetType() on a dynamic) crashes under NativeAOT.
Taking the same route through the IL front-end — Microsoft.CSharp and System.Linq.Expressions compiled from the shared
framework’s IL (ADR 0013) — was measured on a hand-written call site: over ten minutes at -O0, then 159 unsupported
constructs (the Reflection.Emit compiler, full reflection over fields and events, MakeGenericMethod for the update
delegates). Even complete, it would carry the binder (~3.7 MB under NativeAOT) into every program using dynamic and run
an interpreter on every call.
Decision
csharpc binds every dynamic operation at compile time, with Roslyn, once per run-time type that can reach it.
A closed world knows every type a value can have at run time: the types the program has method tables for. For each dynamic operation csharpc emits a site function that switches on the method tables of the dynamic operands; each case calls a function holding the code Roslyn bound for that combination of types.
- Binding = what the runtime binder does. Each case is bound speculatively
(
SemanticModel.TryGetSpeculativeSemanticModel) at the operation’s own source position — the binder’s context for member lookup and accessibility — as a small block that declares a local per operand and evaluates the operation on them:{ global::Point __csdyn0; int __csdyn1; var __csdynr = __csdyn0.@Add(__csdyn1); }. Operands followCSharpArgumentInfo: dynamic ones are locals of the best accessible run-time type, statically typed ones locals of their (substituted) static type, constants are constant expressions of the same type and value, a dynamicnullis the null literal, a struct receiver variable is passed by reference and a boxed struct receiver is the box’s payload (both are mutated, as on .NET). The block’s control-flow graph is lowered like any other. - Which types get a case. Per operand role (ModuleCodeGen.DynamicBinding.cs): a receiver needs a case for every type
with a member of that name (others: the binder’s “does not contain a definition”; types whose lookup stops at
System.Object’s members share one case, called virtually); an argument for every type implicitly convertible to some
candidate parameter other than
object(others bind asobject, which selects the same overload) — and for every type, up to a nesting depth of 2, when a candidate is generic and infers from it; an operator operand for primitives, strings, enums, delegates and types with user-defined operators or conversions (other structs too for==/!=); a conversion for every type with a conversion to the target (reference conversions share one case). On the last dynamic operand, a type whose binding is an error the default case reports identically (naming the run-time type) gets no case:a + bkeeps only the combinations that bind. Reference equality between two “plain” classes is checked at run time (unrelated classes are a binder error). - Errors are the binder’s. A failed binding throws
RuntimeBinderExceptionwith Microsoft.CSharp’s message (Strings.resx), derived from Roslyn’s symbol information: no member, bad argument count or types, ambiguity, static/instance mismatch, inaccessible members, read-only properties, void results, operator and conversion errors. Messages that name a run-time type the case doesn’t know (the default case) are completed at run time from a generated name table. A case csharpc can’t lower (a library member it doesn’t implement yet, for a type the value may never have) throwsNotSupportedExceptionwhen reached instead of failing the compile. - ExpandoObject and DynamicObject follow their meta-objects’ rules in C# that calls
corelib/Dynamic/DynamicObjects.cs: an ExpandoObject’s member get/invoke reads its dictionary first, a set stores; a DynamicObject binds its real members first, then the matchingTry*override (with binders named and shaped like Microsoft.CSharp’s), then the binder’s error. A memberTryInvokeMemberdeclines is fetched withTryGetMemberand invoked dynamically — a dynamic operation inside bound code, bound in the context of the site that contains it. OtherIDynamicMetaObjectProviderimplementations (custom expression-tree meta-objects) are an explicitNotSupportedException. - The fixed point. The set of run-time types grows while the program is lowered (and bound cases can create types), so site bodies are emitted in codegen’s fixed point and re-emitted while a site gains a type it dispatches on; cases are kept across re-emissions. The type-name table is emitted after the fixed point.
dynamicisobjectat run time.CoreLib.Maperases it from every symbol codegen reads, soList<dynamic>,Task<dynamic>anddynamic[]are the same types (layouts, method tables, statics) as theirobjectforms.- Compound assignment is the binder’s.
x op= ybinds as the plainx op y(Microsoft.CSharp mapsAddAssigntoAdd): a dynamic variable takes the result as it is (2 += 0.5is 2.5,short += shortan int), and the store converts it back explicitly, in the checked context — csc’s explicitConvertfor a statically typed variable, the binder’sValueFromCompoundAssignmentset (x = (T)(x op y), T the member’s or indexer’s type) otherwise. Increments keep the operand’s type. (Until 2026-10-31 the operation was bound as a C# compound assignment of a local of the left operand’s run-time type, which narrowed the result of a dynamic variable: sample 761.) - The IL front-end decodes csc’s call sites into the same sites (“From IL” below).
Consequences
dynamicprograms print whatdotnet runprints: samples 680–687 and 760–761 (members, overloads by run-time type, named/optional/ params/ref/out arguments, constructors, generic inference, operators, conversions, indexers, events, delegates, struct receivers, ExpandoObject, DynamicObject, generic code, lambdas, iterators, async, field initializers, binder errors); BCL types (DateTime, TimeSpan, tuples, KeyValuePair); an explicit rejection ofawaiton a dynamic value (687); both corpus programs that usedynamic(using-dynamic, which NativeAOT runs;built-in-types, which it doesn’t).- Speed: a bound case is a type test and a direct call — no binder, no rule cache, no interpreter. A loop of 5M
acc += p.Add(i); p.X = i & 7;ondynamicvalues takes 62–70 ms with csharpc, 308–403 ms on the JIT; NativeAOT can’t run it (2026-10-30, shared VPS). - Size is pay-for-play: programs without
dynamiccompile to byte-identical executables (hello, linq, theinterpreterandjsonprograms, againstmain) in the same time. A program using it pays for the cases of its sites (-O2): the benchmark is 234 KB andusing-dynamic28 KB (NativeAOT: 3.7–3.8 MB for anydynamicprogram); sample 681 (75 sites) 523 KB, sample 680 (~130 sites, many with two dynamic operands) 896 KB, sample 683 (ExpandoObject and DynamicObject from System.Linq.Expressions’ IL) 1.26 MB. - Compile time grows with sites × relevant types: sample 681 compiles in 12 s at
-O2, sample 680 in 35 s (CSHARPC_DYNAMIC_TRACE=1prints per-site planning and emission times;=2also each case). - Not supported yet, each an explicit diagnostic or NotSupportedException:
awaiton a dynamic value, a dynamic value passed byref/out, a simple-name dynamic call through a struct’sthiswhose candidates are both static and instance methods, generic inference with a type nested deeper than 2, run-time types csharpc can’t name (generic types over anonymous types), customIDynamicMetaObjectProviders, and run-time types csharpc has no table for (tasks share one method table acrossTask<T>).
From IL (2026-10-31)
A program given as IL (csharpc app.dll, ADR 0010) or a library consumed as IL carries csc’s call sites instead of
Roslyn’s operations. csharpc turns them into the same DynamicSites, and binds them with the same code.
- Decoding (
FunctionCodeGen.IlDynamic.cs). csc caches each site in a staticCallSite<TDelegate>field of a nested<>o__Nclass, created behindldsfld site; brtrue(Debug:brfalse; br) from constants only:Binder.InvokeMember/GetMember/SetMember/GetIndex/SetIndex/Invoke/InvokeConstructor/BinaryOperation/UnaryOperation/ Convert/IsEvent(flags, name, typeArgs, typeof(Context), new[] { CSharpArgumentInfo.Create(flags, name), ... }), thenldsfld site; ldfld Target; ldsfld site; operands; callvirt TDelegate::Invoke. A pre-pass evaluates each creation (constants,typeof, arrays, the factories) into a description; the guard folds like a feature switch (the creation is never lowered: no binder, noCallSite), the field loads are compile-time markers, and theInvokeis the call of the site’s dispatch function. The operands’ static types are the delegate’s parameter types;CSharpArgumentInfoFlagsgive Dynamic / Static (UseCompileTimeType) / Constant (theldcvalue) / named /ref/outoperands andIsStaticTypereceivers (Console.WriteLine(d),new T(d));CSharpBinderFlagsgiveInvokeSimpleName(csc passesthis),ResultDiscarded,CheckedContext,ConvertExplicit,BinaryOperationLogical(&&/||),ValueFromCompoundAssignment, andInvokeSpecialName(add_E/remove_EafterIsEvent);ExpressionTypegives the operator. Values a site needs at compile time — the site,typeofoperands, constants — stay known across the branches csc puts around the creation of nested sites. A creation in any other shape,ConvertArrayIndex, a constant csharpc can’t read and aGetAwaitercall on a dynamic value are explicit diagnostics. - Binding (
ModuleCodeGen.DynamicIl.cs). A source site binds at its own position, whose accessibility is its context type’s; an IL site’s context is a metadata type, inside which no position exists. IL sites bind in a synthesized method (Frontend/DynamicBinding.Il.cs; added to the binding compilation only when an IL assembly references the binder, so other programs compile exactly as before) throughCompilation.GetSemanticModel(tree, ignoreAccessibility: true), and the real context’s accessibility (IsSymbolAccessibleWithin(member, context, throughType)) is applied on top: lookups that feed planning and messages (simple names,IsEvent, accessors) filter by it; a binding that succeeds must use only members the context can access — then it is the binder’s, since an accessible best member stays best when inaccessible candidates leave the set; a binding error stands only when the context can access every candidate member (removing one could turn an ambiguity into a call). Anything else is aNotSupportedExceptionwhere that case runs. Simple names always name their receiver (thisas a local of its type, or the type for static candidates; both at once:NotSupportedException). Types csc generated (anonymous types, iterators) are ordinary metadata types from IL, which the bound text names through placeholders swapped for their metadata names after parsing. Binder messages of an IL library’s sites name run-time types as that library sees them (its own type-name table).
Samples 680–687 and 760–761 pass through tests/run.sh --via-il at -O0 and -O2; tests/projects/il/IlDynamicApp runs
the dynamic code of an IL library against dotnet run (private and internal members of the library, the app’s
internal types seen as object).