Note that there are some explanatory texts on larger screens.

plurals
  1. POFactory method for generic interface
    primarykey
    data
    text
    <p>I think this code is mortally wounded but would like some opinions before I take a new approach. </p> <p>I am writing a factory method for the following interface.</p> <pre><code>public interface ITransformer&lt;I, O&gt; { O Transform(I input); } </code></pre> <p>Here is a possible implementation of the interface</p> <pre><code>public class CarToTruckTransformer : ITransformer&lt;Car, Truck&gt; { public Truck Transform(Car input) { Truck output = new Truck(); output.Seats = input.Seats - 2; output.BedSize = input.TrunkSize; output.Gunrack = true; return output; } } </code></pre> <p>The first factory I did looks like this</p> <pre><code>static class TransformerFactory { public static ITransformer&lt;I, O&gt; GetTransformer&lt;I, O&gt;() { if (typeof(I) == typeof(Car) &amp;&amp; typeof(O) == typeof(Truck)) { return (ITransformer&lt;I, O&gt;)new CarToTruckTransformer(); } else { return null; } } } </code></pre> <p>But I have to know the exact types when I call the factory method so it seems less than ideal.</p> <pre><code>ITransformer&lt;Car, Truck&gt; transf = TransformerFactory.GetTransformer&lt;Car, Truck&gt;(); </code></pre> <p>I have also toyed with the following, but I'm afraid this may be a gross misuse of the dynamic keyword.</p> <pre><code>public class TransformerFactory2 { public static dynamic GetTransformer(VehicleBase input, VehicleBase output) { if (input.GetType() == typeof(Car) &amp;&amp; output.GetType() == typeof(Truck)) { return (ITransformer&lt;Car, Truck&gt;)new CarToTruckTransformer(); } else { return null; } } } </code></pre> <p>But it does allow me to get the factory syntax that I want.</p> <pre><code>dynamic transf = TransformerFactory2.GetTransformer(car, truck); </code></pre> <p>I've also considered the first option but calling the factory method with reflection so I could dynamically assign the type variables.</p> <p>Ultimately, I would like the entire "transform" process to be contained in one reusable method and just implement new transformers when needed but I'm not there yet.<br> Is there a better or safer approach for this kind of situation?</p> <p>Thanks for reading.</p>
    singulars
    1. This table or related slice is empty.
    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.
 

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