Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find out how many objects are created of a class

Tags:

c#

object

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

like image 633
Prady Avatar asked Mar 06 '10 09:03

Prady


People also ask

How many objects are there in a class?

Why do we need to create more than one object of a class as we can only use one object to access different methods of a class? In principle, infinitely many. In practice, as many objects as fit into the computer's memory.

How many objects are created in Java?

So, only 1 object is ever created because Java is pass-by-reference.

How many objects of a given class can be constructed?

A class is the part of an object that contains the variables. How many objects of a given class may be constructed in a program? A. Only one object is constructed per run of the program.


1 Answers

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?

like image 186
Jon Skeet Avatar answered Sep 27 '22 18:09

Jon Skeet