17

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.

AustinWBryan
  • 3,249
  • 3
  • 24
  • 42
Tomas
  • 17,551
  • 43
  • 152
  • 257
  • define "active", what do you mean by destroyed. – Jodrell Sep 05 '12 at 07:39
  • 6
    boring people would declare a static int variable increasing on construction and decrease on deletion. – Najzero Sep 05 '12 at 07:40
  • looks like a duplicate question to me, and so many duplicate answers. – Jodrell Sep 05 '12 at 07:49
  • This is just for debugging some issue yes, not something you're going to do for real? – Jon Hanna Sep 05 '12 at 07:55
  • @Najzero: Boring people? I dont see your answer. – Nikhil Agrawal Sep 05 '12 at 07:59
  • @ Nikhil Agrawal: fingers were faster than brain and added that comment instead of a answer. Since someoneelse gave that static code in an answer I remain silent ;-). For the boring, I have seen many approaches of "objectManager" classes to do that (feels fancier than a static int variable...), thats why I said boring. – Najzero Sep 05 '12 at 08:01
  • No, there is nothing within C# or .NET that supports this. Also, I struggle to see a practical application for it? Every 'active', i.e. referenced object is reachable by your own code, so you can create your own counting mechanism. – ColinE Sep 05 '12 at 07:40
  • Practical usage would be for performance counter and memory leaks tracking using PostSharp+SmartInspect. – Tomas Sep 05 '12 at 07:42

9 Answers9

29

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

Community
  • 1
  • 1
Dor Cohen
  • 16,769
  • 23
  • 93
  • 161
  • 2
    +1 for the use of `lock` – Yannick Blondeau Sep 05 '12 at 07:47
  • @YannickBlondeau: `lock` should *always* target a `private` field though. If you are going to do it, then do it right. – Jon Sep 05 '12 at 07:50
  • 8
    No. Never put a lock in a finaliser. You don't want the finaliser thread blocking for any reason. Use `Interlocked.Increment` and `Interlocked.Decrement` if you must do something like this from a finaliser. – Jon Hanna Sep 05 '12 at 07:53
  • I get `The modifier 'public' is not valid for this item` on the finalizer line when trying to compile, because finalizers cannot have access modifiers. – Zack Apr 17 '15 at 17:09
7

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();
Habib Zare
  • 1,206
  • 8
  • 17
  • unary operators aren't thread-safe, so this approach will work fine only when objects are constructed in one thread – AntonK Apr 07 '23 at 15:30
4

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.

Jon
  • 428,835
  • 81
  • 738
  • 806
2

Try this one:

public class MyClass
{
    public static int activeCount = 0;

    public MyClass() => activeCount++;
    ~MyClass() => activeCount--;
}


//In the main
var testClass1 = new MyClass();
var testClass2 = new MyClass();

Console.WriteLine(MyClass.activeCount);
AustinWBryan
  • 3,249
  • 3
  • 24
  • 42
Adil Mammadov
  • 8,476
  • 4
  • 31
  • 59
1
public class MyClass
{
    private static int count;
    private static object _lock = new object();

    public MyClass()
    {
         lock(_lock)
         {
             count++;
         }
     }

    private ~MyClass()
    {
        lock(_lock)
        {
             count--;
        }
    }
}
AustinWBryan
  • 3,249
  • 3
  • 24
  • 42
Esben Skov Pedersen
  • 4,437
  • 2
  • 32
  • 46
1
 public class MyClass
    {
public  static int countinstance  =0;
MyClass(){ countinstance  ++;}
 ~ MyClass() {countinstance  --; }
    }

simple and easy get instance active by countinstance

0

I don't know of a built in mechanism, but you can always incrase a private static variable in constructor.

public class MyClass
{
    private static int instances = 0;

    public MyClass() => instances++;
    ~MyClass() => instances--;
}

Haven't tried but should work.

AustinWBryan
  • 3,249
  • 3
  • 24
  • 42
Can Poyrazoğlu
  • 33,241
  • 48
  • 191
  • 389
0

Such thing is not possible but you can do something like

Note : ClassInstance can be also int value just to maintain count.

public class MyType 
{
    public static List<MyType> ClassInstance = new List<MyType>();

    public MyType() => ClassInstance.Add(this);
    public RemoveClass(MyType t)
    {
        ClassInstance.Remove(t);
        t = null;
    }

    public int ActiveCount => ClassInstance.Count;
}
AustinWBryan
  • 3,249
  • 3
  • 24
  • 42
Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
-1

You can try it by making a static variable for count in class and increment it in constructor and decrement in destructor.May this helps you.

SMK
  • 2,098
  • 2
  • 13
  • 21