By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,569 Members | 1,630 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,569 IT Pros & Developers. It's quick & easy.

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

P: n/a
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.

Nov 21 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
Comments inline:

<jc*****@southwestwater.co.uk> wrote in message
news:11**********************@g14g2000cwa.googlegr oups.com...
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
Nov 21 '05 #2

P: n/a
Hi Nick,

That worked a treat. Thanks very much for your help.

Cheers
John.

Nov 21 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.