Late Binding - Myths and Reality
Written by Mike James   
Friday, 05 July 2024
Article Index
Late Binding - Myths and Reality
Dynamic C#
Inheritance and Conditional Casting
Real late binding

Dynamic C#

The dynamic type was introduced in C# 4.

Basically if you declare a reference to be dynamic then this is like declaring it to be object but you can attempt to use any methods or properties you care to.

For example, assuming the same class definitions as before you can write:

dynamic late;
late = new Class1();
int count = late.Method1("Hello World");

In this case the use of Method1 succeeds.

As in that case if the method or property that you try to use doesn't exist then the result is a runtime error.

Reflection based late binding

Suppose that in the C# example we really need to use late binding in a complex and sophisticated way.

Then the standard solution is to use reflection to dynamically discover the type and the other properties of the instance that we want to make use of.

The key to this is the Type class in the System.Reflection name space, so add:

using System.Reflection;

The first thing we need is a type object representing the instance stored in late:

Type T = late.GetType();

Next we need a parameter array containing the parameters we want to pass to the method we are about to call. In this case we need a single element containing the string:

object[] param=new object[1];
param[0]="Hello World";

With all of this set up we simply use the InvokeMember method:

int count= (int)T.InvokeMember(
            BindingFlags.InvokeMethod |
             BindingFlags.Public |

This calls the specified member “Method1”, using its specified type, i.e. a public instance method, using default bindings belonging to the object referenced by late passing the parameters in param.

This all works very nicely but guess what happens if you try to access a member that doesn’t exist.

You generate a runtime error!

Also notice the strange double standards being applied to the late binding of the inputs - the method name and its parameters - and the rather more casual approach to the outputs - the object returned as a result.

Do we bother to use reflection to discover what the result is and to access it?

No, we simply cast it to an int because we know what type is it.



Last Updated ( Friday, 05 July 2024 )