Glossary / dynamic

dynamic

The C# dynamic type defers member lookup, overload resolution, and many conversions from compile time to runtime. It can simplify interoperability with COM, dynamic-language objects, or genuinely runtime-shaped data, but it gives up static checking for operations involving the dynamic value and failures surface during execution.

Runtime binding

dynamic value = "hello";
Console.WriteLine(value.ToUpper());
// value.MissingMethod(); compiles, then fails at runtime

dynamic is represented as object plus compiler metadata and runtime binder behavior; it is not a distinct CLR runtime type. Values can convert to and from dynamic, and operations with dynamic operands are bound at runtime. var is different: it infers a fixed compile-time type. Reflection is also different: it explicitly inspects metadata and invokes members through APIs.

Runtime binding may fail with binder exceptions for missing members, incompatible arguments, or ambiguous overloads. Dynamic invocation can add overhead and obscure refactoring, nullability, and API discovery. It does not validate untrusted input or make arbitrary data safe.

Engineering guidance

Confine dynamic use to narrow boundaries and convert into validated, strongly typed domain models immediately. Add tests for runtime shapes and failure cases. For JSON, prefer a serializer into typed DTOs or JsonDocument/JsonElement with explicit checks. For COM, dynamic can reduce ceremony but requires robust handling of version and automation errors.

Interview questions

  1. dynamic vs var? Dynamic operations bind at runtime; var infers a static type at compile time.
  2. Is dynamic a CLR type? It is represented as object with compiler/runtime binder metadata.
  3. When does a missing member fail? At runtime when the binder attempts the operation.
  4. Does dynamic validate external data? No.
  5. How contain risk? Use it at an interop boundary, validate and convert to typed models, and test shape variations.

References