Sina Karvandi
Sina Karvandi

Reputation: 1102

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

Upvotes: 1

Views: 7268

Answers (3)

General-Doomer
General-Doomer

Reputation: 2761

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'

Upvotes: 5

Damien_The_Unbeliever
Damien_The_Unbeliever

Reputation: 239794

You need to supply a name in your GetType(name) call - at the moment, you're calling the standard GetType() that every object implements and so you're getting the Assembly type - and that doesn't have a MyMethod method.

Upvotes: 2

xanatos
xanatos

Reputation: 111930

This

myDllAssembly.GetType()

is wrong... it will return the typeof(Assembly)

you have to use the overload

myDllAssembly.GetType("ClassOfMyMethod")

Upvotes: 4

Related Questions