How can I find out how many objects are created of a class in C#?
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.
So, only 1 object is ever created because Java is pass-by-reference.
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.
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:
System.String
created, for example - at least not without hooking into the debugging/profiling APIWhy do you want this information, out of interest?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With