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

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.
 
M

Marc Gravell

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
 
M

Marc Gravell

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top