Search code examples
c#late-bindingmissingmethodexception

Late binding MissingMethodException


I'm learning C#, currently in the late binding chapter. I wrote the following for test but it generates MissingMethodException. I loaded a custom private DLL and invoked a method successfully and then I tried to do the same with a GAC DLL but I failed.

I don't know what's wrong with the following code:

//Load the assembly
Assembly dll = Assembly.Load(@"System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 ");

//Get the MessageBox type
Type msBox = dll.GetType("System.Windows.Forms.MessageBox");

//Make an instance of it
object msb = Activator.CreateInstance(msBox);

//Finally invoke the Show method
msBox.GetMethod("Show").Invoke(msb, new object[] { "Hi", "Message" });

Solution

  • You are getting a MissingMethodException on this line:

    object msb = Activator.CreateInstance(msBox);
    

    Because there is no public constructor on the MessageBox class. This class is supposed to be used via its static methods like this:

    MessageBox.Show("Hi", "Message");
    

    To invoke a static method via reflection, you can pass null as the first parameter to the Invoke method like this:

    //Load the assembly
    Assembly dll =
        Assembly.Load(
            @"System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 ");
    
    //Get the MessageBox type
    Type msBox = dll.GetType("System.Windows.Forms.MessageBox");
    
    //Finally invoke the Show method
    msBox
        .GetMethod(
            "Show",
            //We need to find the method that takes two string parameters
            new [] {typeof(string), typeof(string)})
        .Invoke(
            null, //For static methods
            new object[] { "Hi", "Message" });