Generics in C# – how can I create an instance of a variable type with an argument? [duplicate]

Take a look at Activator.CreateInstance. For instance:

var instance = Activator.CreateInstance(typeof(T), new object[] { null, null });

Obviously replacing the nulls 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;

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)