| Show Download Count (Public): | |
Activator.CreateInstanceFromIf your assembly is not loaded yet:
ObjectHandle handle = Activator.CreateInstanceFrom("MyLibrary.dll", "MyNamespace.MyClass");
object instance = handle.Unwrap();
Type t = typeof(List<string>);
object list = Activator.CreateInstance(t);
Console.WriteLine(list.GetType().Name); // Output: List`1
In the era of .NET 4.6.1, the Activator class acted as the universal mechanic. It was the tool the runtime used to bridge the gap between "knowing of a type" and "having an instance of that type."
The most common method in this story is Activator.CreateInstance. activators dotnet 4.6.1
Here is how the story plays out in code:
Type type = typeof(StringBuilder);
object[] args = "Hello, ", 20 ;
object sb = Activator.CreateInstance(type, args);
// Equivalent to: new StringBuilder("Hello, ", 20)
While Activator is convenient, for high-performance scenarios (e.g., creating millions of objects), you should cache a delegate. Demystifying
Solution for .NET 4.6.1: Pre-compiled constructor delegates
public static class ObjectFactory private static Dictionary<Type, Func<object>> _cache = new Dictionary<Type, Func<object>>();public static T Create<T>() Type t = typeof(T); if (!_cache.ContainsKey(t)) var ctor = t.GetConstructor(Type.EmptyTypes); var lambda = Expression.Lambda<Func<object>>( Expression.New(ctor)); _cache[t] = lambda.Compile(); return (T)_cache[t]();
In .NET 4.6.1, Expression lambdas are significantly faster than repeated Activator.CreateInstance calls. The Mechanic of
System.Activator (.NET 4.6.1)| Method | Description |
|--------|-------------|
| CreateInstance(Type) | Creates an instance of the specified type using its parameterless constructor. |
| CreateInstance(Type, object[]) | Creates an instance using the constructor that best matches the specified arguments. |
| CreateInstance<T>() | Generic version; creates an instance of T using the parameterless constructor (requires new() constraint). |
| CreateInstanceFrom(string assemblyFile, string typeName) | Loads an assembly file and creates an instance of the named type. |
| GetObject(Type) | Creates an instance of a COM object (remoting scenario). |
Note: .NET 4.6.1 does not include
ActivatorUtilities(that came with .NET Core / later .NET).