using System; public class SampleService public void Execute() => Console.WriteLine("Service executed successfully."); class Program static void Main() Type targetType = typeof(SampleService); // Dynamically create the instance SampleService service = (SampleService)Activator.CreateInstance(targetType); service.Execute(); Use code with caution. 2. Creating Instances with Constructor Parameters
By the time developers reached the 4.6.1 timeframe, Generics were standard, but they added a new twist to the story. How do you create a List when you only know T at runtime?
Advanced Activation: CreateInstanceFrom and Remote Activation activators dotnet 4.6.1
Use Activator.CreateInstance(Type) for simple plugin loading where configuration dictates the type at runtime.
// Type cannot be loaded (invalid assembly) How do you create a List when you only know T at runtime
public static class ActivatorCache private static readonly ConcurrentDictionary > Cache = new ConcurrentDictionary >(); public static object Create(Type type) return Cache.GetOrAdd(type, t => NewExpression newExp = Expression.New(t); Expression > lambda = Expression.Lambda >(newExp); return lambda.Compile(); )(); Use code with caution. Security and Exception Handling
Think of an IActivator as a custom pipeline that participates in "activating," or creating instances of, objects that can be communicated with across different processes or even different computers on a network. It's a low-level control mechanism for .NET Remoting, a predecessor to modern technologies like WCF. The IActivator interface is marked as supported through .NET Framework 4.8.1, but for the vast majority of developers building standard apps, this is not a tool you will interact with. Security and Exception Handling Think of an IActivator
But as software grew more complex (especially in .NET 4.6.1, which introduced robust support for dynamic compilation and sophisticated dependency injection), developers faced a dilemma. They found themselves writing frameworks and engines where they didn't know what object they needed to create until the program was actually running.
To advance our discussion on dynamic architecture in .NET 4.6.1, let me know if you would like to explore , see a complete benchmarking script using BenchmarkDotNet , or dive into handling internal constructors with private reflection . Share public link
You can compile a lambda expression at runtime to create a highly optimized delegate that performs nearly as fast as the new keyword.