Count instances of the class

You can holds global static counter in your program.
This is a simple thread safe solution:

class MyClass
{
    static int counter = 0;

    public MyClass()
    {
        Interlocked.Increment(ref counter);
    }

    ~MyClass()
    {
        Interlocked.Decrement(ref counter);
    }
}

also take a look at the following similar question - Count number of objects of class type within class method


this :

public class MyClass
{
    private static int instances = 0;

    public MyClass()
    {
        instances++;
    }

    ~MyClass()
    {
        instances--;
    }


    public static int GetActiveInstances()
    {
        return instances;
    }

}

use :

     MyClass c1 = new MyClass();
     MyClass c2 = new MyClass();

     int count = MyClass.GetActiveInstances();

Only if you implement a counting mechanism inside the constructor (increment) and finalizer (decrement). But even that will not account for instances which are really inactive (noone has any reference to them) but have not been collected yet.

Moreover, adding a finalizer to a class -- no matter how trivial -- will adversely affect performance, which is an argument against doing so.