How to create an instance for a given Type?
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>();
Comments
-
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 about 13 years+1 for the second approach. I really like this one :)
-
Brian Hinchey about 11 yearsIf the type is known at compile time, then you might as well use Activator.CreateInstance<T>().
-
nawfal almost 11 yearsWhy wouldn't you not mention
Activator.CreateInstanc<T>()
? -
nawfal almost 11 yearswhy restrict to classes? :)
-
Jon Skeet almost 11 years@nawfal: Because the OP doesn't know
T
- only aType
(as an execution-time value). -
nawfal almost 11 yearsJon yes, the last line of the question confused me.
-
jgauffin almost 11 years@nawfal: Value objects are for unicorns.
-
Hanfeng over 10 yearsIf 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