Type1 and Type2 both inherit from the BaseType abstract class both of which require the same name and type of arguments to be instantiated.

Wouldn’t it be nice to have a generic method like

TypeCreator<T>(int a, int b) where T : BaseType

{

// instantiate type with a and b

}

Now I show you different ways to implement this.

Solutions

1) Using Activator.CreateInstance… – anti-pattern

The simplest way to implement this would be to use the Activator.CreateInstance method. There are numerous articles which says this approach has an awful performance and avoid it but I’d just like to show how it simply works:

For this approach to work, you’d need to provide a delegate to all your types in a Factory then use it. So it’s a bit inflexible as it has to know which types it can instantiate but it should have a very good performance:

The static constructor of the MyTypeFactory class only runs once per application domain the first time the factory is accessed so it should also be thread-safe.

You can simply use it like this:

var type1 = MyTypeFactory.Create<Type1>(1, 2);

3) Using Expression Trees

In this approach, a lambda expression has to be compiled per type. So for each type a new compilation will be done initially then they're stored in a private field for further reuse. This has much better performance in comparison with Activator.CreateInstance.

Another good point about this approach is its flexibility; you don’t have to hard code the constructors like approach 2.