Disclaimer: Theoretical Question
The new constraint specifies that any type argument in a generic class declaration must have a public parameterless constructor.
Source: http://msdn.microsoft.com/en-us/library/sd2w2ew5(v=vs.80).aspx
What if I wanted my generic class to have a protected parameterless constructor instead? For instance, if I want to write a Singleton
class which I "attach" to other classes to make them Singleton
s, I don't want the derived classes to be instantiable - everything should go through the .Instance
property.
internal class Singleton<T> where T : new()
{
public static T Instance { get; private set; }
static Singleton()
{
Singleton<T>.Instance = new T();
}
}
internal class OnlyOneOfMe : Singleton<OnlyOneOfMe>
{
protected OnlyOneOfMe()
{
}
}
This way, Singleton<T>
is able to create the only instance of the OnlyOneOfMe
class, but nothing else can (unless it is a subclass).
"What if a generic parent class could access the generic type's protected members?"