24

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?

Jader Dias
  • 88,211
  • 155
  • 421
  • 625

2 Answers2

27

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
18

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>();
jgauffin
  • 99,844
  • 45
  • 235
  • 372