<p>No, this is not a question about generics.</p>

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

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

<p>Example</p>

<pre><code>// Fails
Activator.CreateInstance(type);

// Works
Activator.CreateInstance(type, true);
</code></pre>

<p>I wanted to make the factory generic to make it a little simpler, like this:</p>

<pre><code>public class GenericFactory&lt;T&gt; where T : MyAbstractType
{
    public static T GetInstance()
    {
        return Activator.CreateInstance&lt;T&gt;();
    }
}
</code></pre>

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

<p>Did I miss something or it isn't possible?</p>

[{'answer_id': 57450, 'author': 'Kilhoffer', 'author_id': 5469, 'author_profile': 'https://Stackoverflow.com/users/5469', 'pm_score': 5, 'selected': True, 'text': '<p>To get around this, couldnt you just alter your usage as such:</p>\n\n<pre><code>public class GenericFactory&lt;T&gt; where T : MyAbstractType\n{\n    public static T GetInstance()\n    {\n        return Activator.CreateInstance(typeof(T), true);\n    }\n}\n</code></pre>\n\n<p>Your factory method will still be generic, but the call to the activator will not use the generic overload. But you should still achieve the same results.</p>\n'}, {'answer_id': 57463, 'author': 'rpetrich', 'author_id': 4007, 'author_profile': 'https://Stackoverflow.com/users/4007', 'pm_score': 2, 'selected': False, 'text': "<p>If you absolutely require that the constructor be private you can try something like this:</p>\n\n<pre><code>public abstract class GenericFactory&lt;T&gt; where T : MyAbstractType\n{\n    public static T GetInstance()\n    {\n        return (T)Activator.CreateInstance(typeof(T), true);\n    }\n}\n</code></pre>\n\n<p>Otherwise you're best off adding the new constraint and going that route:</p>\n\n<pre><code>public abstract class GenericFactory&lt;T&gt; where T : MyAbstractType, new()\n{\n    public static T GetInstance()\n    {\n        return new T;\n    }\n}\n</code></pre>\n\n<p>You're trying to use GenericFactory as a base class for all of your factories rather than writing each from scratch right?</p>\n"}, {'answer_id': 3032285, 'author': 'mpastern', 'author_id': 365684, 'author_profile': 'https://Stackoverflow.com/users/365684', 'pm_score': 0, 'selected': False, 'text': '<p>besides Activator.CreateInstance(typeof(T), true) to work, T should have default constructor</p>\n'}]
['https://Stackoverflow.com/questions/57439', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1782/']