How can I count the number of objects of a class type within a method of that class? For that matter, how to do it outside of a class without adding the objects to a list?>
Do you mean in a way that would allow you to track how many times you had called new MyClass()
such that there are N instances taking up memory at the moment, and you want to know the value of N?
If you want to track memory usage, use the debugger to dump the state of the heap. The thing is, the answer will depend on the GC and whether it has collected unreferenced objects.
You could have a counter you increment in the constructor, but when to decrement it? Finalizers run in another thread, which underlines the unpredictability of this whole idea. Might be better to implement IDisposable
to decrement the counter, and require the objects to be Disposed when not needed.