c# - Initialize generic type with non-empty constructor -


referencing question: cannot create instance of variable type 'item' because not have new() constraint

i create instance generic type non empty constructor.

public class a{};  public class b {    public b(int){/*...*/} }  public class c {    public static t validate<t>(int index)        t : a,        new(int) //error    {       if(/*validation*/)          return null;       return new t(index);    } } 

if try call b b = validate<b>(42); got error:

'b' must non-abstract type public parameterless constructor in order use parameter 't' in generic type or method 'c.validate(int)'

question 1: why can use parameterless constructors only?

question 2: how can solve problem without delegates or interfaces? (i looking fancy solutions.)

you can use reflection invoke constructor:

var constructorinfo = typeof(t).getconstructor(new[] { typeof(int) }); if (constructorinfo != null) {     object[] parameters = new object[] { index };     return (t)constructorinfo.invoke(parameters); } else {   // handle } 

(adapted https://stackoverflow.com/a/13523659/5962841)


or, can use activator create instance (see @datrax's answer)

(t)activator.createinstance(typeof(t), index) 

the feature asked has been requested.

the request feature being tracked here (github csharp design repo), don't expect year, it's not prototyped or accepted.


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -