Dynamic Binding
Dynamic binding defers binding—the process of resolving types, members, and operations—from compile time to runtime. Dynamic binding was introduced in C# 4.0, and is useful when at compile time you know that a certain function, member, or operation exists, but the compiler does not. This commonly occurs when you are interoperating with dynamic languages (such as IronPython) and COM and in scenarios when you might otherwise use reflection.
A dynamic type is declared with the contextual keyword dynamic
:
dynamic d = GetSomeObject(); d.Quack();
A dynamic type tells the compiler to relax. We expect the runtime
type of d
to have a Quack
method. We just can’t prove it statically.
Since d
is dynamic, the compiler defers
binding Quack
to d
until runtime. To understand what this means
requires distinguishing between static binding and
dynamic binding.
Static Binding Versus Dynamic Binding
The canonical binding example is mapping a name to a specific
function when compiling an expression. To compile the following expression, the compiler needs
to find the implementation of the
method named Quack
:
d.Quack();
Let’s suppose the static type of d
is Duck
:
Duck d = ... d.Quack();
In the simplest case, the compiler does the binding by looking for
a parameterless method named Quack
on
Duck
. Failing that, the compiler
extends its search to methods taking optional parameters, methods on
base classes of Duck
, and extension
methods that take Duck
as its first parameter. If no match is found, you’ll ...
Get C# 5.0 Pocket Reference now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.