0

I got some troubles with Activator.CreateInstance. It throws "Constructor on type not found" exception.

Here is the method where error occurs:

private static void InitializeInternalProperty(Calculation calculation, Type type, IDataProvider dataProvider, params string[] precedants)
{
    PropertiesCollection precedantsCollection = new PropertiesCollection(); //Properties collection implements IKeyedCollection
    foreach (string precedant in precedants)
    {
        precedantsCollection.Add(calculation.properties[precedant]);
    }
    calculation.properties.Add((Property)Activator.CreateInstance(type, dataProvider, precedantsCollection));
}

Here is the constructor, i am trying to use:

internal CountryRiskPremium(IDataProvider dataProvider, PropertiesCollection precedants)
{
    Name = Names.CountryRiskPremium;
    InitLinks(precedants);
    _dataProvider = dataProvider;
}

I also tried:

object[] arguments = new object[2];
arguments[0] = dataProvider;
arguments[1] = precedantsCollection;
calculation.properties.Add((Property)Activator.CreateInstance(type, arguments));
I.R.
  • 442
  • 1
  • 7
  • 16

1 Answers1

2

Activator only works with public constructors, with the simple overload of CreateInstance that you are using. For using private/protected/internal constructors, you need to use another overload. See https://learn.microsoft.com/en-us/dotnet/api/system.activator.createinstance.

Ricardo Peres
  • 13,724
  • 5
  • 57
  • 74