7

How can I find out how many objects are created of a class in C#?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Prady
  • 10,978
  • 39
  • 124
  • 176

2 Answers2

13

You'd have to put a static counter in that was incremented on construction:

public class Foo
{
    private static long instanceCount;

    public Foo()
    {
        // Increment in atomic and thread-safe manner
        Interlocked.Increment(ref instanceCount);
    }
}

A couple of notes:

  • This doesn't count the number of currently in memory instances - that would involve having a finalizer to decrement the counter; I wouldn't recommend that
  • This won't include instances created via some mechanisms like serialization which may bypass a constructor
  • Obviously this only works if you can modify the class; you can't find out the number of instances of System.String created, for example - at least not without hooking into the debugging/profiling API

Why do you want this information, out of interest?

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 1
    How about `Interlocked.Decrement(ref instanceCount)` in destructor of the object? Then `instanceCount` will give an estimate of currently living object instances. – user Jul 01 '13 at 01:15
  • Agreed, it's useful to decrement within the destructor for finalization. `~Foo() { Interlocked.Decrement(ref instanceCount); }` @JonSkeet, why wouldn't you recommend that (out of interest)? – defines Oct 09 '15 at 13:35
  • 1
    @defines: Because that's counting something different - that's counting how many objects haven't been finalized. The OP was asking for the number of objects that had been created. If I create 100 and they're all finalized/GC'd, I've still created 100 objects. – Jon Skeet Oct 09 '15 at 13:38
  • True. In my usage I wanted to look at current objects in memory which haven't been GC'd, while debugging. Based on OP's wording that would be different, you're right. But your answer seems to say you wouldn't recommend counting currently in memory instances; I thought you were cautioning against it and wondered why. – defines Oct 09 '15 at 13:39
1

Is this a class that you've designed?

If so, add a counter to the class that is incremented in the constructor and decremented in Dispose.

Potentially you could make this a performance counter so you can track it in Performance Monitor.

Michael Shimmins
  • 19,961
  • 7
  • 57
  • 90