Search code examples
c#factory-patterngenericsobject-construction

Create generic class with internal constructor


Is it possible to construct an object with its internal constructor within a generic method?

public abstract class FooBase { }

public class Foo : FooBase {
   internal Foo() { }
}

public static class FooFactory {
    public static TFooResult CreateFoo<TFooResult>()
    where TFooResult : FooBase, new() {
        return new TFooResult();
    }
}

FooFactory resides in the same assembly as Foo. Classes call the factory method like this:

var foo = FooFactory.CreateFoo<Foo>();

They get the compile-time error:

'Foo' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'TFooType' in the generic type or method 'FooFactory.CreateFoo()'

Is there any way to get around this?

I also tried:

Activator.CreateInstance<TFooResult>(); 

This raises the same error at runtime.


Solution

  • You could remove the new() constraint and return:

    //uses overload with non-public set to true
    (TFooResult) Activator.CreateInstance(typeof(TFooResult), true); 
    

    although the client could do that too. This, however, is prone to runtime errors.

    This is a hard problem to solve in a safe manner since the language does not permit an abstract constructor declaraton.