Number of instances in parent and child classes

I have a parent type, and there are some types of children inheriting it.

I want to make sure that there is only one instance of the parent, as well as for all types of children. Parent Type:

private static int _instanceCount = 0; public ParentClass() { protected ParentClass() // constructor { _instanceCount++; if (_instanceCount > 1) throw new exception("Only one instance is allowed."); } } 

Example 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 types of children, but when they call the constructor of the base class, I cannot tell if the base constructor is called from other types or not, so the solution does not work.

How can i achieve this?

+4
source share
4 answers

You should be able to determine if you are called from a subclass, for example:

 if( this.GetType().Equals(typeof(ParentClass)) ) { //we know we're not being called by a sub-class. } 

Of course, you can just skip the step of increasing the counter in the child classes and do it only in the parent ... and there are problems with threads.

+2
source

Looks like you want Singleton functionality.

+1
source

Perhaps there are other ways to approach what you are trying to do, for example, using singletones, but one way to make sure that calling the base constructor does not give you a false positive result is to check its type, for example

 protected ParentClass() { if (!GetType().Equal(typeof(ParentClass))) { // The child class has taken care of the check aleady return; } } 
+1
source

ok ... this can be a very bad hack ... but you can get the stack trace from Environment.StackTrace and see if your child class was called shortly before your constructor code was run. lol ... good luck! :)

0
source

All Articles