tags:

views:

99

answers:

1

I need to create an parameterless instance for a Generic Class in C#.

How to do this.

+6  A: 

You could add the : new() constraint:

void Foo<T>() where T : class, new() {
    T newT = new T();
    // do something shiny with newT
}

If you don't have the constraint, then Activator.CreateInstance<T> may help (minus the compile-time checking):

void Foo<T>() {
    T newT = Activator.CreateInstance<T>();
    // do something shiny with newT
}

If you mean you the type itself, then probably something like:

Type itemType = typeof(int);
IList list = (IList)Activator.CreateInstance(
         typeof(List<>).MakeGenericType(itemType));
Marc Gravell
+1 It may be interesting to point out that both code examples do the same thing at execution-time (i.e. use the `Activator` class). You do call out compile-time checking but you may want to explain a bit more about what you mean.
Andrew Hare
@Andrew Hare: Interesting point! I would have assumed T newT = new T() would be done when the type-specific Foo<T> code is generated.
Jimmy
To follow up on Andrew's point; the `: new()` constraint allows calling code to be sanity checked when you hit "build", but in reality it boils down to the same IL (for various implementation details). It'll work fine without it, but if you call `Foo<string>`, then expect pain.
Marc Gravell
@Marc - I wish I could upvote again - nicely done :)
Andrew Hare