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 WeakReference
class. For example...
public class MyClass
{
private static List<WeakReference> instances = new List<WeakReference>();
public MyClass()
{
instances.Add(new WeakReference(this));
}
public static IList<MyClass> GetInstances()
{
List<MyClass> realInstances = new List<MyClass>();
List<WeakReference> toDelete = new List<WeakReference>();
foreach(WeakReference reference in instances)
{
if(reference.IsAlive)
{
realInstances.Add((MyClass)reference.Target);
}
else
{
toDelete.Add(reference);
}
}
foreach(WeakReference reference in toDelete) instances.Remove(reference);
return realInstances;
}
}
Since you're new to OO/.NET, don't let the WeakReference
use 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. The WeakReference
is a special class allows you to maintain a reference to an object that the garbage collector will ignore. The IsAlive
property indicates whether or not the WeakReference
is pointing to a valid object that still exists.
So what we do here is keep this list of WeakReference
s that point to every instance of MyClass
that's been created. When you want to obtain a list of them, we iterate through our WeakReference
s 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 the WeakReference
class itself can be collected and our list doesn't grow huge without reason).