In C#, how to instantiate a passed generic type inside a method?

Couple of ways.

Without specifying the type must have a constructor:

T obj = default(T); //which will produce null for reference types

With a constructor:

T obj = new T();

But this requires the clause:

where T : new()

Declare your method like this:

public string InstantiateType<T>(string firstName, string lastName) 
              where T : IPerson, new()

Notice the additional constraint at the end. Then create a new instance in the method body:

T obj = new T();    

you want new T(), but you'll also need to add , new() to the where spec for the factory method


To extend on the answers above, adding where T:new() constraint to a generic method will require T to have a public, parameterless constructor.

If you want to avoid that - and in a factory pattern you sometimes force the others to go through your factory method and not directly through the constructor - then the alternative is to use reflection (Activator.CreateInstance...) and keep the default constructor private. But this comes with a performance penalty, of course.

Tags:

C#

Generics