I’ve created a generic class that needs to instantiate its implementation type, so the implementation type has to have an accessible parameter less constructor. Looks like the new() restriction could do the job but its enforcing the implementation type to have a public constructor when I have it internal (but accessible as both are on the same assembly).
- Is there a reason to force it to be public rather than “accessible”?
- Is there a way to do what I need?
Thanks in advance.
EDIT: The reason to do this is that I have a class X that must be used through a Singleton. The Singleton class is a generic class and I want to make the class X constructor internal to avoid external users accessing the object in a wrong way (calling the constructor).
This is disallowed by the C# language as outlined in section 4.4.3 of the specification Bound and Unbound Types.
A compiler error if any one of these conditions are not met. If you find yourself having types that are public but only with internal constructors, then most likely they should actually be internal types with public constructors.
I would recommend changing your types accessor to
internaland its constructor’s topublic, and make it parameterless. Yourpublicparameterless constructor could then call through to a non-parameterlessprivateorinternalconstructor to do any additional initialization work.Mind you that pattern is limited, but there’s nothing stopping you from using a
privatemethod instead.As per your update, here’s a small example of a public singleton patter.
Usage
You don’t even need to use constructors in that fashion either, you can just as easily do something simple.
Generics may not be the way to go if you can’t design it to fit your requirements. Generics can only do so much and don’t solve every problem. There are things like Factory Pattern, Injection, etc..