Dynamically create an object of <Type>

public static T GetInstance<T>(params object[] args)
{
     return (T)Activator.CreateInstance(typeof(T), args);
}

I would use Activator.CreateInstance() instead of casting, as the Activator has a constructor for generics.


If the type is known by the caller, there's a better, faster way than using Activator.CreateInstance: you can instead use a generic constraint on the method that specifies it has a default parameterless constructor.

Doing it this way is type-safe and doesn't require reflection.

T CreateType<T>() where T : new()
{
   return new T();
}

This link should help:
https://docs.microsoft.com/en-us/dotnet/api/system.activator.createinstance

Activator.CreateInstance will create an instance of the specified type.

You could wrap that in a generic method like this:

public T GetInstance<T>(string type)
{
    return (T)Activator.CreateInstance(Type.GetType(type));
}

Tags:

C#

.Net

Dynamic