CSharp/C# Tutorial - C# Dynamic Binding






Dynamic binding defers the process of resolving types, members, and operations from compile time to runtime.

A dynamic type is declared with the contextual keyword dynamic:


dynamic d = GetSomeObject();
d.OneMethod();

A dynamic type expects the runtime type of d to have a OneMethod method.

Since d is dynamic, the compiler defers binding OneMethod to d until runtime.

Dynamic Conversions

The dynamic type has implicit conversions to and from all other types:


int i = 7;
dynamic d = i;
long j = d; // No cast required (implicit conversion)

For the conversion to succeed, the runtime type of the dynamic object must be implicitly convertible to the target static type.

The following example throws a RuntimeBinderException because an int is not implicitly convertible to a short:


int i = 7;
dynamic d = i;
short j = d; // throws RuntimeBinderException





var vs dynamic

var makes the compiler to figure out the type.

dynamic makes the runtime to figure out the type."

To illustrate:


dynamic x = "hello"; // Static type is dynamic, runtime type is string
var y = "hello";     // Static type is string, runtime type is string

int i = x; // Runtime error
int j = y; // Compile-time error

The static type of a variable declared with var can be dynamic:


dynamic x = "hello";
var y = x; // Static type of y is dynamic
int z = y; // Runtime error





Dynamic Expressions

Fields, properties, methods, events, constructors, indexers, operators, and conversions can all be called dynamically.

Expressions involving dynamic operands are typically themselves dynamic:


dynamic x = 2;
var y = x * 3; // Static type of y is dynamic

casting a dynamic expression to a static type yields a static expression:


dynamic x = 2;
var y = (int)x; // Static type of y is int

Constructor invocations always yield static expressions.

In this example, x is statically typed to a StringBuilder:


dynamic capacity = 1;
var x = new System.Text.StringBuilder (capacity);