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

StackOverflow https://stackoverflow.com/questions/10796062

Question

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?

Was it helpful?

Solution

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top