How to Activator.CreateInstance an object with an internal parametrizedconstructor.

  • Thread starter Thread starter Frank Rizzo
  • Start date Start date
F

Frank Rizzo

Hello, I have the following object:

public class Report
{
public Report() {}
internal Report (bool IgnoreCriteria) { // do stuff }
}

From another assembly I am loading this Report object via
Activator.CreateInstance method.

I've tried the following code:

Type availableReport = Reports.FirstRptType(); //returns a Report Type
object[] constructorParameter = new object[] { true };
Report reportPlugin = Activator.CreateInstance(availableReport,
constructorParameter) as Report;

This fails with Missing method exception, obviously because it cannot
find the internal constructor. If I switch the internal constructor to
be public, everything is fine.

However, I'd like the constructor to be internal. Is there a way to
instantiate the object with the internal constructor?

Thanks.
 
Not via Activator, but...

Report rep = (Report) availableReport.GetConstructor(
BindingFlags.NonPublic | BindingFlags.Instance,
null, new Type[] {typeof(bool)},null
).Invoke(new object[] {false});

Note: I don't recommend messing with reflection for this type of thing
unless you are (for instance) writing a plugin architecture; for
regular referenced code, it smacks of a poor design decision.

Marc
 
unless you are (for instance) writing a plugin architecture

....and belatedly I noticed the name "reportPlugin" - in which case
this might be reasonable ;-p

Marc
 
Back
Top