Skip to content

Dynamic binding C# 4.0new scenarios

Defer type resolution until runtime.

C# is a statically-typed language - all operations in your code are checked at compile-time to ensure the methods and properties exist and that objects are of the correct type when passed around. This contrasts to dynamic languages where such checking is deferred to the very last second before the operation is performed.

C# 4 introduces the dynamic object type which behaves much like object but defers all type-checking to runtime.

This is very useful when dealing with external libraries that will return an object to you which can be one of a number of types without an interface or shared common base type but that will have the same method signature.

Code

C#
object launcher = getLauncher(launcherName);
try {
    launcher.Execute(args);
}
catch {
    throw new NotSupportedException(launcherName + " does not support Execute");
}
C#
object launcher = getLauncher(launcherName);
if (launcher.GetType() == typeof(WindowsShellExecutor)) {
    ((WindowsShellExecutor)launcher).Execute(args);
} else
if (launcher.GetType() == typeof(MacLaunchServices)) {
    ((MacLaunchServices)launcher).Execute(args);
} else
if (launcher.GetType() == typeof(GnomeRunner)) {
    ((GnomeRunner)launcher).Execute(args);
} else {
    throw new NotSupportedException(launcherName + " (probably) does not support Execute");
}

Notes

  • Dynamic support in .NET came out of the IronRuby and IronPython projects - Ruby and Python are both dynamic languages and so required it

  • C# picked it up and uses it for COM interop in C#

  • At runtime you will receive an exception message if the dynamic object is not suitable. This could be:

    When a dynamic object does not have the property or method accessed at runtime:

    'object' does not contain a definition for 'MethodOrProperty'

    When a dynamic object is not the right type to be used as a parameter to a method:

    The best overloaded method match for 'Namespace.Class.Method(ArgType)' has some invalid arguments

    Or even, in the case of assigning one variable to another when the type is incompatible:

    Cannot implicitly convert type 'object' to 'sometype'. An explicit conversion exists (are you missing a cast?)

All of these are Microsoft.CSharp.RuntimeBinder.RuntimeBinderException with HResult=0x80131500.

More information