Click to See Complete Forum and Search --> : Activator createinstance with parameter


yolip
April 20th, 2009, 09:17 PM
Hi, I learnt the below code from here before, it works fine when i just loading up the dll that has no parameter. However, i am now requires to pass the parameter to the calling dll form.

for instance,
Dll name: clsdll.dll
Form in the Dll: public void frmReadint(Int32 intNum)

so how do i change the below code to clsdll.frmReadint ?

Thanks

private void Call_External_Project(string AssemblyName, string TypeName)
{
try
{
Assembly thisAssembly = Assembly.LoadFrom(AssemblyName);

Type type = thisAssembly.GetType(TypeName);
object instance = Activator.CreateInstance(type);

ConstructorInfo constructor;

//call without parameter
constructor = type.GetConstructor(System.Type.EmptyTypes);
Form objForm = (Form)constructor.Invoke(null); //((Form)constructor.Invoke(null)).Show();
objForm.MdiParent = this;
objForm.Show();

objForm = null;
constructor = null;
instance = null;
type = null;
thisAssembly = null;


}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

MadHatter
April 20th, 2009, 10:17 PM
to create an instance using a constructor that takes a parameter, you simply pass in an args array to Activator.CreateInstance (which in turn gets the appropriate constructor info and invokes it)

public class Foo {
int f = 0;
public Foo(int f) {
this.f = f;
}
}

// create an instance of Foo
Type t = typeof(Foo); // however you get this...
object instance = (Foo)Activator.CreateInstance(t, new object[] { 32 });