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?
I should have thought of that! Thanks! I’m gonna leave it unanswered for a little while to see if there is a better way, because I agree. I’m just sortv wrapping my head around OO. If you don’t mind let me explain a little more and maybe there is a better way in general?
I have an object class that i want to add 3 pieces of information to, but first I want to cycle through and make sure there are no other objects with any of the three pieces the same, and if there are, do something different for each case.
The only way to accomplish what you’re looking for is to keep a static list of these objects in the class itself. If you just want to see if there is an instance somewhere that hasn’t been garbage collected, then you’ll want to use the
WeakReferenceclass. For example…Since you’re new to OO/.NET, don’t let the
WeakReferenceuse scare you. The way garbage collection works is by reference counting. As long as some piece of code or an object has access to a particular instance (meaning it’s within scope as a or as part of a local, instance, or static variable) then that object is considered alive. Once that variable falls OUT of scope, at some point after that the garbage collector can/will collect it. However, if you were to maintain a list of all references, they would never fall out of scope since they would exist as references in that list. TheWeakReferenceis a special class allows you to maintain a reference to an object that the garbage collector will ignore. TheIsAliveproperty indicates whether or not theWeakReferenceis pointing to a valid object that still exists.So what we do here is keep this list of
WeakReferences that point to every instance ofMyClassthat’s been created. When you want to obtain a list of them, we iterate through ourWeakReferences and snatch out all of them that are alive. Any we find that are no longer alive are placed into another temporary list so that we can delete them from our outer list (so that theWeakReferenceclass itself can be collected and our list doesn’t grow huge without reason).