A C# payroll import reads rows as dynamic, and a misspelled row.Salry compiles but throws; how do dynamic, var and object differ?
answer
- when is the member checked
- dynamic compiles to object plus call sites
- RuntimeBinderException on a bad bind
- results stay dynamic
- no extension methods, no lambdas
basics
~20 svar is a compile-time inferred type and object is a static type exposing only object's members; the compiler checks both. dynamic skips compile-time checking: each operation is bound at run time on the actual type, so a typo throws RuntimeBinderException.
solid answer
~50 s`var` infers a static type, so `row.Salry` on an `Employee` fails with CS1061; `object` is static too, so even `row.Salary` fails with CS1061 until you cast. `dynamic` compiles to `object` plus call sites: the compiler records the member name and arguments, and the C# runtime binder resolves them against the run-time type when the line executes, throwing `RuntimeBinderException` on a mistake. Results of dynamic operations are dynamic too, so `var annual = row.Salary * 12;` is dynamic and errors in later code also wait for run time. Overloads are picked by run-time types, extension methods are not found, and a lambda argument is CS1977. Each call site caches its binding, but the first bind is costly, and the trim and AOT analyzers flag every dynamic operation. Bind rows to a typed record at the boundary.
code
csharp · 23 lines#:property PublishAot=false
using System;
using Microsoft.CSharp.RuntimeBinder;
dynamic row = new Employee("Ada", 4200m);
var annual = row.Salary * 12;
Console.WriteLine(Payroll.Describe(annual));
try
{
Console.WriteLine(row.Salry);
}
catch (RuntimeBinderException ex)
{
Console.WriteLine($"{ex.GetType().Name}: {ex.Message}");
}
record Employee(string Name, decimal Salary);
static class Payroll
{
public static string Describe(object value) => $"object overload: {value}";
public static string Describe(decimal value) => $"decimal overload: {value}";
}go deeper
Recall that var is inferred at compile time, object is a static type with only object's members, and dynamic defers member binding to run time.
Explain what the compiler emits for dynamic, call sites and the C# runtime binder, and why results stay dynamic until converted to a static type.
Diagnose a run-time RuntimeBinderException in an import: trace how dynamic spread through var locals, then convert to typed records at the boundary and list the binder's blind spots.
Decide where dynamic is acceptable in a codebase: interop boundaries only, never domain logic, and never in code meant for trimming or Native AOT.
## Three declarations, three compile-time stories | Declaration | Compile-time type | `row.Salary` | `row.Salry` (a typo) | |---|---|---|---| | `var row = new Employee(...)` | `Employee` | compiles | CS1061 at compile time | | `object row = new Employee(...)` | `object` | CS1061 until you cast | CS1061 at compile time | | `dynamic row = new Employee(...)` | `dynamic` | bound at run time | `RuntimeBinderException` at run time | `var` is plain inference: the local's static type is `Employee`, and the compiler checks every member. `object` is an explicit static type that exposes only `object`'s members (`ToString`, `Equals`, `GetHashCode`, `GetType`); calling `Salary` on it fails with **CS1061** ("'object' does not contain a definition for 'Salary' and no accessible extension method 'Salary' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)") until you cast. `dynamic` tells the compiler not to resolve or type-check operations on the expression at all. ## What the compiler emits for `dynamic` `dynamic` exists only at compile time; in the compiled code a `dynamic` local is an `object`. The difference is in how each operation on it is compiled: - Each dynamic operation (member access, call, operator, conversion) becomes a **call site**: a `CallSite<T>` object held in a static field of a compiler-generated class and created the first time the line runs. - When the line runs, the call site asks the **C# runtime binder** (`Microsoft.CSharp.RuntimeBinder`) to bind the operation with C# rules, using the **run-time types** of the receiver and arguments. - The call site caches what the binder produced, so a later execution with the same run-time types skips the binder. The first bind is the expensive part, and a value type stored in a `dynamic` is boxed, as it would be in an `object`. - If binding fails, the binder throws `RuntimeBinderException`, for example "'Employee' does not contain a definition for 'Salry'". ## How `dynamic` spreads The result of most dynamic operations is itself `dynamic`. `var annual = row.Salary * 12;` makes `annual` a `dynamic` local, so a typo on `annual` also compiles and fails later. The exceptions are conversions from `dynamic` to a static type and constructor calls with dynamic arguments: `decimal salary = row.Salary;` gives a statically typed `decimal`, and compile-time checking resumes from there. In a payroll import, one `dynamic` row can quietly turn every downstream calculation into run-time-bound code unless a typed variable stops it. ## Run-time binding surprises - **Overload resolution moves to run time** when the receiver or any argument is dynamic, and uses run-time types: `Payroll.Describe(annual)` picks a `Describe(decimal)` overload over `Describe(object)`. - **Extension methods are not found**: the runtime binder does not know which `using` directives were in scope, so `list.First()` on a dynamic `List<int>` throws `RuntimeBinderException` even with `using System.Linq;`. Call `Enumerable.First(list)` or cast first. - **Lambdas cannot be arguments** to a dynamically dispatched call: **CS1977** "Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type." - **Target-typed `new()`** has no target there either: `d.AddRange(new())` is CS8754. ## Trimming and Native AOT The runtime binder relies on reflection and run-time code generation. When a build runs the trim and AOT analyzers (for example with `PublishAot` set), each dynamic operation is reported with **IL2026**, because the binder's members carry `RequiresUnreferencedCodeAttribute`, and **IL3050**, whose text says "The 'dynamic' feature requires runtime-code generation, which is incompatible with AOT." ## Fixing the import 1. Bind each row to a typed `record`, such as `Employee(string Name, decimal Salary)`, at the boundary where data enters. 2. If a `dynamic` value must flow in, convert it to a static type on the first line that touches it. 3. Keep `dynamic` for what it was designed for, such as COM interop and objects from dynamic languages, where there is no static type to bind against.
- Why does `list.First()` throw when `list` is `dynamic`, even with `using System.Linq;` at the top of the file?Extension methods are found by the compiler from the `using` directives in scope, and that information is not passed to the runtime binder. At run time the binder looks only at `List<int>`'s own members, finds no `First`, and throws `RuntimeBinderException` ("'System.Collections.Generic.List<int>' does not contain a definition for 'First'"). Call `Enumerable.First(list)` as a static method, or cast `list` to a static type first.
- Is a `dynamic` call slow every time it runs?Not every time. The compiler stores a `CallSite<T>` per operation in a static field, and the call site caches the binding the C# runtime binder produced. The first execution pays for the bind; later executions with the same run-time types reuse the cached result. It is still slower than a statically bound call, value types stored in `dynamic` are boxed, and the trim and AOT analyzers flag every dynamic operation.
- var and dynamic both decide the type at run time
- object lets you call the run-time type's members without a cast
- The compiler still catches a misspelled member on a dynamic receiver
- Assigning a dynamic result to var makes it statically typed
- dynamic finds extension methods through the file's using directives
- dynamic calls choose overloads at compile time like normal calls