views:

38

answers:

1

I've got a piece of code in a project (MyProject) that contains early bound object from a referenced assembly (We'll call it CommonAssembly):

Dim myObject As CommonAssembly.MyEarlyBoundType

now I have another assembly that is dynamically loaded because it is not present in all projects:

Dim myLateBoundObject As Object = AppDomain.CurrentDomain.CreateInstanceAndUnwrap("Utils", "Utils.MyLateBoundType")

MyLateBoundType derives from CommonAssembly.MyEarlyBoundType, and I want to cast myObject to myLateBoundObject and then programmatically invoke the additional member methods via reflection. I'd have thought that by extracting the type of myLateBoundOject and casting myObject into myLateBoundObject, that'd work, but both CType() and DirectCast() methods won't accept the extracted type citing a "Keyword does not name a type" error:

myLateBoundObject = DirectCast(myObject, GetType(myLateBoundObject))

I'm not entirely sure why a dynamically loaded type cannot be used against the DirectCast (pretty sure it's not type saftey checked?) method, since if Utils.MyLateBoundType was referenced in "MyPrjoect", I could execute:

myLateBoundObject = DirectCast(myObject, Utils.MyLateBoundType)

without any problems - but this is not a dynamic solution.

Any suggestions?

Cheers,

Yum.

A: 

Yeah, that's not going to work like that. Any attempt you'd make in your code to cast to the dynamically loaded type will make your program have a non-dynamic dependency on the assembly.

You should use an interface type. Declare that type, with all the properties and methods you'd want to have available in your main program, in a separate assembly. Both your main program and your plug-in will have a dependency on it. The dynamic type should inherit it to provide the implementation. You can now cast the return value of CreateInstance to that interface type.

Hans Passant
Yep, that seems a lot tider way to go about it. Cheers!
Yumbelie