<p>Is there a way?</p>

<p>I need all types that implement a specific interface to have a parameterless constructor, can it be done?</p>

<p>I am developing the base code for other developers in my company to use in a specific project.</p>

<p>There's a proccess which will create instances of types (in different threads) that perform certain tasks, and I need those types to follow a specific contract (ergo, the interface).</p>

<p>The interface will be internal to the assembly</p>

<p>If you have a suggestion for this scenario without interfaces, I'll gladly take it into consideration...</p>

[{'answer_id': 26909, 'author': 'Vaibhav', 'author_id': 380, 'author_profile': 'https://Stackoverflow.com/users/380', 'pm_score': 0, 'selected': False, 'text': "<p>I don't think so. </p>\n\n<p>You also can't use an abstract class for this.</p>\n"}, {'answer_id': 26928, 'author': 'Brad Wilson', 'author_id': 1554, 'author_profile': 'https://Stackoverflow.com/users/1554', 'pm_score': 5, 'selected': False, 'text': "<p>Not to be too blunt, but you've misunderstood the purpose of interfaces.</p>\n\n<p>An interface means that several people can implement it in their own classes, and then pass instances of those classes to other classes to be used. Creation creates an unnecessary strong coupling.</p>\n\n<p>It sounds like you really need some kind of registration system, either to have people register instances of usable classes that implement the interface, or of factories that can create said items upon request.</p>\n"}, {'answer_id': 26997, 'author': 'Chris Ammerman', 'author_id': 2729, 'author_profile': 'https://Stackoverflow.com/users/2729', 'pm_score': 3, 'selected': False, 'text': '<p>Juan,</p>\n\n<p>Unfortunately there is no way to get around this in a strongly typed language.  You won\'t be able to ensure at compile time that the classes will be able to be instantiated by your Activator-based code.</p>\n\n<p>(ed: removed an erroneous alternative solution)</p>\n\n<p>The reason is that, unfortunately, it\'s not possible to use interfaces, abstract classes, or virtual methods in combination with either constructors or static methods.  The short reason is that the former contain no explicit type information, and the latter require explicit type information.</p>\n\n<p>Constructors and static methods <strong>must</strong> have explicit (right there in the code) type information available at the time of the call.  This is required because there is no instance of the class involved which can be queried by the runtime to obtain the underlying type, which the runtime needs to determine which actual concrete method to call.</p>\n\n<p>The entire point of an interface, abstract class, or virtual method is to be able to make a function call <strong>without</strong> explicit type information, and this is enabled by the fact that there is an instance being referenced, which has "hidden" type information not directly available to the calling code.  So these two mechanisms are quite simply mutually exclusive.  They can\'t be used together because when you mix them, you end up with no concrete type information at all anywhere, which means the runtime has no idea where to find the function you\'re asking it to call.</p>\n'}, {'answer_id': 27031, 'author': 'Frank Krueger', 'author_id': 338, 'author_profile': 'https://Stackoverflow.com/users/338', 'pm_score': 0, 'selected': False, 'text': "<p>I would like to remind everyone that:</p>\n\n<ol>\n<li>Writing attributes in .NET is easy</li>\n<li>Writing static analysis tools in .NET that ensure conformance with company standards is easy</li>\n</ol>\n\n<p>Writing a tool to grab all concrete classes that implement a certain interface/have an attribute and verifying that it has a parameterless constructor takes about 5 mins of coding effort. You add it to your post-build step and now you have a framework for whatever other static analyses you need to perform.</p>\n\n<p>The language, the compiler, the IDE, your brain - they're all tools. Use them!</p>\n"}, {'answer_id': 27047, 'author': 'aku', 'author_id': 1196, 'author_profile': 'https://Stackoverflow.com/users/1196', 'pm_score': 3, 'selected': False, 'text': '<p>You can use <a href="https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/constraints-on-type-parameters" rel="nofollow noreferrer">type parameter constraint</a></p>\n<pre class="lang-csharp prettyprint-override"><code>interface ITest&lt;T&gt; where T: new()\n{\n    //...\n}\n\nclass Test: ITest&lt;Test&gt;\n{\n    //...\n}\n</code></pre>\n'}, {'answer_id': 27049, 'author': 'Landon Kuhn', 'author_id': 1785, 'author_profile': 'https://Stackoverflow.com/users/1785', 'pm_score': 0, 'selected': False, 'text': "<p>No you can't do that. Maybe for your situation a factory interface would be helpful? Something like:</p>\n\n<pre><code>interface FooFactory {\n    Foo createInstance();\n}\n</code></pre>\n\n<p>For every implementation of Foo you create an instance of FooFactory that knows how to create it.</p>\n"}, {'answer_id': 27058, 'author': 'Andrei Rînea', 'author_id': 1796, 'author_profile': 'https://Stackoverflow.com/users/1796', 'pm_score': 0, 'selected': False, 'text': '<p>You do not need a parameterless constructor for the Activator to instantiate your class. You can have a parameterized constructor and pass all the parameters from the Activator. Check out <a href="http://msdn.microsoft.com/en-us/library/4b0ww1we.aspx" rel="nofollow noreferrer">MSDN on this</a>.</p>\n'}, {'answer_id': 27454, 'author': 'Chris Ammerman', 'author_id': 2729, 'author_profile': 'https://Stackoverflow.com/users/2729', 'pm_score': 4, 'selected': True, 'text': '<p><a href="https://stackoverflow.com/questions/26903/how-can-you-require-a-constructor-with-no-parameters-for-types-implementing-an#27386">Juan Manuel said:</a></p>\n\n<blockquote>\n  <p>that\'s one of the reasons I don\'t understand why it cannot be a part of the contract in the interface</p>\n</blockquote>\n\n<p>It\'s an indirect mechanism.  The generic allows you to "cheat" and send type information along with the interface.  The critical thing to remember here is that the constraint isn\'t on the interface that you are working with directly.  It\'s not a constraint on the interface itself, but on some other type that will "ride along" on the interface.  This is the best explanation I can offer, I\'m afraid.</p>\n\n<p>By way of illustration of this fact, I\'ll point out a hole that I have noticed in aku\'s code.  It\'s possible to write a class that would compile fine but fail at runtime when you try to instantiate it:</p>\n\n<pre><code>public class Something : ITest&lt;String&gt;\n{\n  private Something() { }\n}\n</code></pre>\n\n<p>Something derives from ITest&lt;T&gt;, but implements no parameterless constructor.  It will compile fine, because String does implement a parameterless constructor.  Again, the constraint is on T, and therefore String, rather than ITest or Something.  Since the constraint on T is satisfied, this will compile.  But it will fail at runtime.</p>\n\n<p>To prevent <strong>some</strong> instances of this problem, you need to add another constraint to T, as below:</p>\n\n<pre><code>public interface ITest&lt;T&gt;\n  where T : ITest&lt;T&gt;, new()\n{\n}\n</code></pre>\n\n<p>Note the new constraint: T : ITest&lt;T&gt;. This constraint specifies that what you pass into the argument parameter of ITest&lt;T&gt; <strong>must</strong> also <strong>derive</strong> from ITest&lt;T&gt;.</p>\n\n<p>Even so this will not prevent <strong>all</strong> cases of the hole.  The code below will compile fine, because A has a parameterless constructor.  But since B\'s parameterless constructor is private, instantiating B with your process will fail at runtime.</p>\n\n<pre><code>public class A : ITest&lt;A&gt;\n{\n}\n\npublic class B : ITest&lt;A&gt;\n{\n  private B() { }\n}\n</code></pre>\n'}, {'answer_id': 36919, 'author': 'Mark Brackett', 'author_id': 2199, 'author_profile': 'https://Stackoverflow.com/users/2199', 'pm_score': 1, 'selected': False, 'text': '<p>Call a RegisterType method with the type, and constrain it using generics. Then, instead of walking assemblies to find ITest implementors, just store them and create from there.</p>\n\n<pre><code>void RegisterType&lt;T&gt;() where T:ITest, new() {\n}\n</code></pre>\n'}, {'answer_id': 68357, 'author': 'munificent', 'author_id': 9457, 'author_profile': 'https://Stackoverflow.com/users/9457', 'pm_score': 2, 'selected': False, 'text': "<p>So you need a <em>thing</em> that can create instances of an unknown type that implements an interface. You've got basically three options: a factory object, a Type object, or a delegate. Here's the givens:</p>\n\n<pre><code>public interface IInterface\n{\n    void DoSomething();\n}\n\npublic class Foo : IInterface\n{\n    public void DoSomething() { /* whatever */ }\n}\n</code></pre>\n\n<p>Using Type is pretty ugly, but makes sense in some scenarios:</p>\n\n<pre><code>public IInterface CreateUsingType(Type thingThatCreates)\n{\n    ConstructorInfo constructor = thingThatCreates.GetConstructor(Type.EmptyTypes);\n    return (IInterface)constructor.Invoke(new object[0]);\n}\n\npublic void Test()\n{\n    IInterface thing = CreateUsingType(typeof(Foo));\n}\n</code></pre>\n\n<p>The biggest problem with it, is that at compile time, you have no guarantee that Foo actually <em>has</em> a default constructor. Also, reflection is a bit slow if this happens to be performance critical code.</p>\n\n<p>The most common solution is to use a factory:</p>\n\n<pre><code>public interface IFactory\n{\n    IInterface Create();\n}\n\npublic class Factory&lt;T&gt; where T : IInterface, new()\n{\n    public IInterface Create() { return new T(); }\n}\n\npublic IInterface CreateUsingFactory(IFactory factory)\n{\n    return factory.Create();\n}\n\npublic void Test()\n{\n    IInterface thing = CreateUsingFactory(new Factory&lt;Foo&gt;());\n}\n</code></pre>\n\n<p>In the above, IFactory is what really matters. Factory is just a convenience class for classes that <em>do</em> provide a default constructor. This is the simplest and often best solution.</p>\n\n<p>The third currently-uncommon-but-likely-to-become-more-common solution is using a delegate:</p>\n\n<pre><code>public IInterface CreateUsingDelegate(Func&lt;IInterface&gt; createCallback)\n{\n    return createCallback();\n}\n\npublic void Test()\n{\n    IInterface thing = CreateUsingDelegate(() =&gt; new Foo());\n}\n</code></pre>\n\n<p>The advantage here is that the code is short and simple, can work with <em>any</em> method of construction, and (with closures) lets you easily pass along additional data needed to construct the objects.</p>\n"}]
['https://Stackoverflow.com/questions/26903', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1782/']