Activator.CreateInstance(string) and Activator.CreateInstance<T>() difference

Posted by Juan Manuel Formoso on Stack Overflow See other posts from Stack Overflow or by Juan Manuel Formoso
Published on 2008-09-11T19:42:33Z Indexed on 2010/06/13 13:02 UTC
Read the original article Hit count: 262

Filed under:
|
|

No, this is not a question about generics.

I have a Factory pattern with several classes with internal constructors (I don't want them being instantiated if not through the factory).

My problem is that CreateInstance fails with a "No parameterless constructor defined for this object" error unless I pass "true" on the non-public parameter.

Example

// Fails
Activator.CreateInstance(type);

// Works
Activator.CreateInstance(type, true);

I wanted to make the factory generic to make it a little simpler, like this:

public class GenericFactory<T> where T : MyAbstractType
{
    public static T GetInstance()
    {
        return Activator.CreateInstance<T>();
    }
}

However, I was unable to find how to pass that "true" parameter for it to accept non-public constructors (internal).

Did I miss something or it isn't possible?

© Stack Overflow or respective owner

Related posts about c#

Related posts about generics