CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Oct 2002
    Location
    Australia
    Posts
    207

    Activator createinstance with parameter

    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);
    }
    }

  2. #2
    Join Date
    Mar 2004
    Location
    33°11'18.10"N 96°45'20.28"W
    Posts
    1,808

    Re: Activator createinstance with parameter

    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)

    Code:
    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 });

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured