(Activator.CreateObject) : Passing parameters to constructor while creating object at run-time

  • Thread starter Thread starter Kürþat
  • Start date Start date
K

Kürþat

Hi,

I want to set a plug-in architecture and need object creation at run-time. I
can create objects at run-time using Activator.CreateObject method, so far
so good. But some objects have constructors other than default one and I
should pass required parameters to use them. Is it possible to instantiate
objects at run-time using non-default construcotors?
 
I'm guessing you mean for a type that isn't known at compile-time; if so,
then by reflection, yes; once you have the Type definition (via Type.GetType
[static] or Assembly.GetType [instance]), call e.g.

Type t = null; // TODO: aquire the type-def
object newObj = t.GetConstructor(new Type[] {typeof(string),
typeof(int)}).Invoke(new object[] {"abc",123});

Marc
 
Kürþat said:
I want to set a plug-in architecture and need object creation at run-time.. I
can create objects at run-time using Activator.CreateObject method, so far
so good. But some objects have constructors other than default one and I
should pass required parameters to use them. Is it possible to instantiate
objects at run-time using non-default construcotors?

Activator.CreateInstance has overloads allowing you to specify the
arguments to pass.
 
Cheers Jon; I must have somehow missed that... that's my "something
new" for today ;-p

Marc
 

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

Back
Top