I have a parent type and there are some children types inheriting from it.
I want to make sure there is only one instance of the parent and also for all the children types. Parent type:
private static int _instanceCount = 0;
public ParentClass()
{
protected ParentClass() // constructor
{
_instanceCount++;
if (_instanceCount > 1)
throw new exception("Only one instance is allowed.");
}
}
Sample child class:
private static int _instanceCount = 0;
public ChildClass() : ParentClass
{
public ChildClass() : base() // constructor
{
_instanceCount++;
if (_instanceCount > 1)
throw new exception("Only one instance is allowed.");
}
}
The solution works for children types but when they call the base class constructor I cannot distinguish if the base constructor is called from other types or not so the solution fails.
How can I achieve this?
You should be able to tell if you’re being called from a subclass like this:
Of course, you could just skip the step of incrementing the count in child classes and only do it in the parent as well…and there are threading issues.