Search code examples
c#reflection.net-assembly

Invoke a method from another assembly


I have Tools.dll file that contains MyMethod() like this :

    public void MyMethod()
    {
        global::System.Windows.Forms.MessageBox.Show("Sth");
    }

Now , I am trying to run this assembly method from another file :

        System.Reflection.Assembly myDllAssembly = System.Reflection.Assembly.LoadFile(@"PATH\Tools.dll");
 myDllAssembly.GetType().GetMethod("MyMethod").Invoke(myDllAssembly, null); //here we invoke MyMethod.

After running 'System.NullReferenceException' happens . It says "Object reference not set to an instance of an object."

So How can I fix it ?!

Im sure this .dll building truth without problem .

Note : the assembly code come from : http://www.codeproject.com/Articles/32828/Using-Reflection-to-load-unreferenced-assemblies-a


Solution

  • Remember, that 'Invoke' requires a class instance for non-static methods, therefore you should use construction like this:

    Type type = myDllAssembly.GetType("TypeName");
    type.GetMethod("MyMethod").Invoke(Activator.CreateInstance(type), null);
    

    Complete example with parameterised constructor and method

    Class code:

    public class MyClass
    {
        private string parameter;
    
        /// <summary>
        /// конструктор
        /// </summary>
        public MyClass(string parameter)
        {
            this.parameter = parameter;
        }
    
        public void MyMethod(string value)
        {
            Console.Write("You parameter is '{0}' and value is '{1}'", parameter, value);
        }
    }
    

    Invokation code:

    Type type = typeof(MyClass);
    // OR
    type = assembly.GetType("MyClass");
    type.GetMethod("MyMethod").Invoke(Activator.CreateInstance(type, "well"), new object[] { "played" });
    

    Result:

    You parameter is 'well' and value is 'played'