3

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

How to do this.

1
  • Do you mean without generic arguments? Like new List<>() ? Commented Mar 15, 2010 at 5:28

1 Answer 1

21

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));
Sign up to request clarification or add additional context in comments.

4 Comments

+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: Interesting point! I would have assumed T newT = new T() would be done when the type-specific Foo<T> code is generated.
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.
@AndrewHare How to call the methods of T type Class "my own class containing method like class myclass{ public DataSet GetRawData(){ DataSet ds = null; return ds; }

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.