How do you dynamically create an instance of a type and invoke a method on it using reflection, when the type isn't known at compile time?
Short answer
Activator.CreateInstance(type) constructs a new instance given a Type object (optionally with constructor arguments), and MethodInfo.Invoke(instance, args) calls a method on that instance dynamically — both essential for plugin systems that load and use types discovered at…
Advertisement
AModel answer
Activator.CreateInstance(type) constructs a new instance given a Type object (optionally with constructor arguments), and MethodInfo.Invoke(instance, args) calls a method on that instance dynamically — both essential for plugin systems that load and use types discovered at runtime.
Type type = Type.GetType("MyApp.Plugins.LoggerPlugin");
object instance = Activator.CreateInstance(type)!;
MethodInfo method = type.GetMethod("Log")!;
method.Invoke(instance, new object[] { "Hello from reflection!" });Real-world example
Building a plugin architecture that loads and instantiates plugin classes discovered dynamically from a directory of DLLs.
Likely follow-ups
- What's the performance cost of Activator.CreateInstance() and MethodInfo.Invoke() compared to a direct 'new' call and method invocation?
Related topics