92

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?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Roman
  • 4,443
  • 14
  • 56
  • 81
  • Are you going to do doing this frequently? What version of C#? – Ben Voigt Jun 20 '11 at 11:26
  • [this](http://stackoverflow.com/questions/840261/c-generic-new-constructor-problem/840299#840299) is the best workaround i've been able to find.... – J. Ed Jun 20 '11 at 11:22
  • Another way is to create a public property on `Some_Base_Class`, and then you can do the following: `new T() { SomeProperty = "value" }` – nZeus Mar 13 '17 at 19:59

1 Answers1

141

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;
p.campbell
  • 98,673
  • 67
  • 256
  • 322
Grant Thomas
  • 44,454
  • 10
  • 85
  • 129