Late Binding - Myths and Reality |
Written by Mike James | ||||||
Friday, 05 July 2024 | ||||||
Page 2 of 5
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:
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 bindingSuppose 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:
The first thing we need is a type object representing the instance stored in late:
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:
With all of this set up we simply use the InvokeMember method:
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. <ASIN: B09FTLPTP9> |
||||||
Last Updated ( Friday, 05 July 2024 ) |