Passing a Delegate to a Constructor using Activator.CreateInstance()

J

jcomber

Hi,

I'd be grateful for some help...

I'm trying to create a late bound object using:

Activator.CreateInstance(Type, ConstructorParameters())

The constructor of the object takes a delegate as the only parameter.
However, ConstructorParameters() is an object array and because a
Delegate is not derived from System.Object, it won't compile.

Here's an example of what I'm trying to achieve:

Dim t As Type = Type.GetType("Namespace.ClassName,AssemblyName")
Dim p() as Object = {AddressOf DelegatedMethod}
Dim o As IObject = DirectCast(Activator.CreateInstance(t, p), IObject)

Is there a work around to this?

TIA for any help.

Regards
John.
 
N

Nick Hall

Comments inline:

Hi,

I'd be grateful for some help...

I'm trying to create a late bound object using:

Activator.CreateInstance(Type, ConstructorParameters())

The constructor of the object takes a delegate as the only parameter.
However, ConstructorParameters() is an object array and because a
Delegate is not derived from System.Object, it won't compile.
This is not true. ALL classes in the framework derive directly or
indirectly from System.Object; therefore an object of any class can be
assigned to a variable of type Object.
Here's an example of what I'm trying to achieve:

Dim t As Type = Type.GetType("Namespace.ClassName,AssemblyName")
Dim p() as Object = {AddressOf DelegatedMethod}
This is your problem. Normally when using the AddressOf operator VB can
infer the type of delegate you are trying to create from the type of the
variable your are assigning the result to and create it automatically. In
this case your are assigning to an Object and VB has no idea what type of
delegate to create. You need to give it a helping hand in this case by
instantiating a specific Delegate type. For instance

Private Delegate Sub MyDelegate()
Dim p() as Object = {New MyDelegate(AddressOf DelegatedMethod)}
Dim o As IObject = DirectCast(Activator.CreateInstance(t, p), IObject)

Is there a work around to this?

TIA for any help.

Regards
John.

Hope this helps,

Nick Hall
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top