Generics in C# - how can I create an instance of a variable type with an argument?
C#GenericsC# Problem Overview
I've got a generics class, where I want to instantiate an object with the generic type. I want to use an argument for the constructor of the type.
My code:
public class GenericClass<T> where T : Some_Base_Class, new()
{
public static T SomeFunction(string s)
{
if (String.IsNullOrEmpty(s))
return new T(some_param);
}
}
I get an error on the
new T(some_param)
> 'T': cannot provide arguments when creating an instance of a variable > type
Any ideas how can I do this?
C# Solutions
Solution 1 - C#
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;