user676853
user676853

Reputation:

Counting how many objects are being used from a class

Simple question really, I just can't seem to find an answer.

How do I go about counting how many objects are being used from a particular class? I was thinking of using a list and adding all the objects to a list and then counting the list... If I was to do that, how would I access that list?

Upvotes: 1

Views: 211

Answers (2)

Jordão
Jordão

Reputation: 56457

There are basically two ways to do this.

  1. Keep a static count in your class that gets incremented on the constructor and decremented on the destructor (and Dispose, if you use IDisposable). The downside of this is that you'll delay garbage collection on your objects because they'll go to the finalization queue (if not using Dispose).

  2. Keep a static list of weak references to your instances. Add this to the list in your constructor. When enumerating the list or counting its elements, check that the weak references are still alive to really count that object. Also, you might want to compact the list at this time, that is, remove its dead weak references. You could take a look at the ConditionalWeakTable<TKey, TValue>, but unfortunately it doesn't provide you a simple count.

Also, think about synchronizing access to those elements if multiple threads can be creating your objects.

Upvotes: 1

Attila
Attila

Reputation: 28762

If you are interested in how many instances of a class have been created, you can increment a static counter in its constructor(s).

public class C
{
  private static int numInstances;
  public C() {
    ++numInstances;
    // and whatever else is needed
  }
}

Note that this code is not thread safe: you will need to add thread safety protections around the accesses to C.numInstances

Upvotes: 1

Related Questions