Just how to create a new object instance from a Type

One might not constantly recognize the Type of an object at compile-time, yet might require to create an instance of the Type. Just how do you get a new object instance from a Type?

0
2019-05-04 21:01:37
Source Share
Answers: 2

One execution of this trouble is to try to call the parameter-less erector of the Type :

public static object GetNewObject(Type t)
{
    try
    {
        return t.GetConstructor(new Type[] { }).Invoke(new object[] { });
    }
    catch
    {
        return null;
    }
}

Below coincides strategy, had in a common method :

public static T GetNewObject<T>()
{
    try
    {
        return (T)typeof(T).GetConstructor(new Type[] { }).Invoke(new object[] { });
    }
    catch
    {
        return default(T);
    }
}
0
2019-05-08 04:28:05
Source

The Activator class within the origin System namespace is rather effective.

There are a great deal of overloads for passing parameters to the erector and also such. Look into the documents at :

http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx

or (new course)

https://docs.microsoft.com/en-us/dotnet/api/system.activator.createinstance

Here are some straightforward instances :

ObjectType instance = (ObjectType)Activator.CreateInstance(objectType);

ObjectType instance = (ObjectType)Activator.CreateInstance("MyAssembly","MyNamespace.ObjectType");
0
2019-05-08 04:09:00
Source