Generics in C# - how can I create an instance of a variable type with an argument? [duplicate]
Solution 1:
Take a look at Activator.CreateInstance
. For instance:
var instance = Activator.CreateInstance(typeof(T), new object[] { null, null });
Obviously replacing the null
s with appropriate values expected by one of the constructors of the type.
If you receive a compiler error about cannot convert object to type T
, then include as T
:
var instance = Activator.CreateInstance(typeof(T),
new object[] { null, null }) as T;