Currently I trace number of instances of a base class this way:
private static int _instanceCount = 0;
protected BaseClass()
{
Interlocked.Increment(ref _instanceCount);
if (_instanceCount > 1)
throw new Exception("multiple instances detected.");
}
Then I have child classes with constructor like this:
public ChildClass(): base()
{
// Empty Constructor
}
and I get exceptions of course. I can move the code from BaseClass
constructor to ChildClass
constructor but it's a kind of redundancy (all children with the same code).
Is there any way to do it in the BaseClass
?
Is getting exception means I really tried to create more than one instance of the ChildClass
according to above code?