Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count instances of the class [duplicate]

Possible Duplicate:
how can i find out how many objects are created of a class in C#

Is it possible to get number of instances which is active(created and not yet destroyed) for selected class?

For example:

public class MyClass { }

...

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

count = GetActiveInstances(typeof(MyClass))

Should return 2. If GC destroy any of these classes then 1 or 0.

like image 906
Tomas Avatar asked Sep 05 '12 07:09

Tomas


People also ask

How do you count duplicate values in a set?

Working with large data sets often requires you to count duplicates in Excel. You can count duplicate values using the COUNTIF function.


1 Answers

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

like image 183
Dor Cohen Avatar answered Sep 24 '22 06:09

Dor Cohen