Dynamic binding defers binding—the process of resolving types, members, and operations—from compile time to runtime. Dynamic binding 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 d = GetSomeObject(); d.Quack();
A dynamic type tells the compiler to relax. We expect the runtime
d to have a
Quack method. We just can’t prove it statically.
d is dynamic, the compiler defers
d until runtime. To understand what this means
requires distinguishing between
static binding and 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
Let’s suppose the static type of
Duck d = ... d.Quack();
In the simplest case, the compiler does the binding by looking for
a parameterless method named
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 a compilation ...