How to fix Activator.CreateInstance failing with MissingMethodException "Constructor on type not found"?

DaveDev picture DaveDev · May 29, 2012 · Viewed 11.4k times · Source

I'm trying to create a custom User Control with the following:

var panel = new GenericAccordionPanel<ZoneReport, ZonesPanel, ZonesVM>(myVm.ZonesVm);

GenericAccordionPanel is defined as:

public class GenericAccordionPanel<THeader, TBody, TViewModel> : UserControl
{
    public Accordion Accordion { get; set; }

    public GenericAccordionPanel(TViewModel vmItem)
    {
        this.Accordion = new Accordion();

        //the constructor for ZoneReport(THeader) takes a ZonesVM (vmItem) as a parameter.
        var zr = (THeader)Activator.CreateInstance(typeof(THeader), new { vmItem });

        var exp = new Expander { Header = zr };

        Accordion.Children.Add(exp);

        base.Content = Accordion;
    }
}

The problem is that Activator.CreateInstance is failing with the following MissingMethodException:

Constructor on type '[namespace].Zones.ZoneReport' not found.

How can I create an isntance of ZoneReport?

Answer

porges picture porges · May 29, 2012

new { vmItem } should be new object[]{ vmItem }.

At the moment you're calling Activator.CreateInstance with an anonymous type as the second argument, not an array of parameters.

Since the second argument (for the overload you want) is actually a params parameter, you can also just use plain vmItem and the compiler will generate the array:

 var zr = (THeader)Activator.CreateInstance(typeof(THeader), vmItem);