How to create an instance for a given Type?

38,140

Solution 1

The closest available is Activator.CreateInstance:

object o = Activator.CreateInstance(type);

... but of course this relies on there being a public parameterless constructor. (Other overloads allow you to specify constructor arguments.)

I've used an explicitly typed variable here to make it clear that we really don't have a variable of the type itself... you can't write:

Type t = typeof(MemoryStream);
// Won't compile
MemoryStream ms = Activator.CreateInstance(t);

for example. The compile-time type of the return value of CreateInstance is always object.

Note that default(T) won't create an instance of a reference type - it gives the default value for the type, which is a null reference for reference types. Compare that with CreateInstance which would actually create a new object.

Solution 2

var myObject = Activator.CreateInstance(myType)

You have to cast if you want to use a typed parameter:

User user = (User)Activator.CreateInstance(typeof(User));

.. or with parameters

User user = (User)Activator.CreateInstance(typeof(User), new object[]{firstName, lastName});

You can also use generics:

public T Create<T>() where T : class, new()
{
    return new T();
}

var user = Create<User>();
Share:
38,140
Jader Dias
Author by

Jader Dias

Perl, Javascript, C#, Go, Matlab and Python Developer

Updated on July 16, 2022

Comments

  • Jader Dias
    Jader Dias almost 2 years

    With generics you can

    var object = default(T);
    

    But when all you have is a Type instance I could only

    constructor = type.GetConstructor(Type.EmptyTypes);
    var parameters = new object[0];
    var obj = constructor.Invoke(parameters);
    

    or even

    var obj = type.GetConstructor(Type.EmptyTypes).Invoke(new object[0]);
    

    Isn't there a shorter way, like the generics version?

  • Jonas Van der Aa
    Jonas Van der Aa about 13 years
    +1 for the second approach. I really like this one :)
  • Brian Hinchey
    Brian Hinchey about 11 years
    If the type is known at compile time, then you might as well use Activator.CreateInstance<T>().
  • nawfal
    nawfal almost 11 years
    Why wouldn't you not mention Activator.CreateInstanc<T>() ?
  • nawfal
    nawfal almost 11 years
    why restrict to classes? :)
  • Jon Skeet
    Jon Skeet almost 11 years
    @nawfal: Because the OP doesn't know T - only a Type (as an execution-time value).
  • nawfal
    nawfal almost 11 years
    Jon yes, the last line of the question confused me.
  • jgauffin
    jgauffin almost 11 years
    @nawfal: Value objects are for unicorns.
  • Hanfeng
    Hanfeng over 10 years
    If I already know the Type User, why shouldn't I use the new method directly, the question is how to create object elegantly only with the System.Type variable