Note that there are some explanatory texts on larger screens.

plurals
  1. POPossible to compile-time check constructor parameters for generic factory function?
    primarykey
    data
    text
    <p>I am experimenting with some factory type code where the BuildIt function returns a concrete type based solely on the generic type passed in. The generic type is restricted to being descendants of the BaseAbstract class.</p> <p>The Buildit function just needs the generic type and then a list of params (the params are used as constructor parameters in the BuildIt function when creating the concrete classes).</p> <p>The example code below works as expected (prints "A" then "B")</p> <p>But the problem happens if I try to call something like:</p> <pre><code> var b = fs.BuildIt&lt;B&gt;("B", "C"); </code></pre> <p>Since the B class doesn't have a constructor with 2 parameters, this fails at runtime. </p> <p>Is it possible to do something like this, except have this fail at compile time? If not, is there another way to go about this so that compile time checking is possible (doesn't matter if all this has to be thrown out and start something completely different)</p> <p><strong>Example Code</strong></p> <pre><code>public abstract class BaseAbstract { public string Name =""; public override string ToString () { return Name; } } public class A : BaseAbstract { public A() { Name = "A"; } } public class B : BaseAbstract { public B() { } public B(string param) { Name = param; } } public class Factory { public T BuildIt&lt;T&gt;(params object[] args) where T : BaseAbstract, new() { T x = (T)Activator.CreateInstance(typeof(T), args); return x; } } public class MainClass { public static void Main (string[] args) { //These are fine Factory fs = new Factory(); var a = fs.BuildIt&lt;A&gt;(); var b = fs.BuildIt&lt;B&gt;("B"); Console.WriteLine (a); Console.WriteLine (b); //This would cause runtime error because of the "C" paramter //var b2 = fs.BuildIt&lt;B&gt;("B", "C"); } } </code></pre>
    singulars
    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