Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    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> <pre><code>public interface IInterface { void DoSomething(); } public class Foo : IInterface { public void DoSomething() { /* whatever */ } } </code></pre> <p>Using Type is pretty ugly, but makes sense in some scenarios:</p> <pre><code>public IInterface CreateUsingType(Type thingThatCreates) { ConstructorInfo constructor = thingThatCreates.GetConstructor(Type.EmptyTypes); return (IInterface)constructor.Invoke(new object[0]); } public void Test() { IInterface thing = CreateUsingType(typeof(Foo)); } </code></pre> <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> <p>The most common solution is to use a factory:</p> <pre><code>public interface IFactory { IInterface Create(); } public class Factory&lt;T&gt; where T : IInterface, new() { public IInterface Create() { return new T(); } } public IInterface CreateUsingFactory(IFactory factory) { return factory.Create(); } public void Test() { IInterface thing = CreateUsingFactory(new Factory&lt;Foo&gt;()); } </code></pre> <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> <p>The third currently-uncommon-but-likely-to-become-more-common solution is using a delegate:</p> <pre><code>public IInterface CreateUsingDelegate(Func&lt;IInterface&gt; createCallback) { return createCallback(); } public void Test() { IInterface thing = CreateUsingDelegate(() =&gt; new Foo()); } </code></pre> <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>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload