Activator.CreateInstance Method

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I have the following code which works fine.
However I want to pass the object I'm instantiating a string for its
constructor.
I can't get the syntax right. Can someone give me an example of
Activator.CreateInstance where they pass an argument with the object type?

Assembly a = Assembly.GetExecutingAssembly();
Type type = a.GetType("MyAssemb.MyClass");
Object o = Activator.CreateInstance(type);
MyClass myObj= (MyClass)Activator.CreateInstance(type, args[]?????);
 
This should do it:

MyClass myObj = (MyClass)Activator.CreateInstance(type, new Object[]
{"string arg"});

Basically, you need to passing an array of objects for the argument(s).

hope that helps..
Imran.
 
Thanks Imran. It works!

Imran Koradia said:
This should do it:

MyClass myObj = (MyClass)Activator.CreateInstance(type, new Object[]
{"string arg"});

Basically, you need to passing an array of objects for the argument(s).

hope that helps..
Imran.

shmeian said:
I have the following code which works fine.
However I want to pass the object I'm instantiating a string for its
constructor.
I can't get the syntax right. Can someone give me an example of
Activator.CreateInstance where they pass an argument with the object type?

Assembly a = Assembly.GetExecutingAssembly();
Type type = a.GetType("MyAssemb.MyClass");
Object o = Activator.CreateInstance(type);
MyClass myObj= (MyClass)Activator.CreateInstance(type, args[]?????);
 
Back
Top