Can reflection get a list of object instances?

Suppose you have a Shape class. Suppose the shape was created as a circle, square and triangle. Is there a runtime way to get a list of the names of Shape objects and then iterate over those objects?

+3


source to share


2 answers


Cannot use reflection to get a list of object instances. Reflection can provide information about the type or interact with the objects you reference, this prevents you from finding "all objects of this type ever created".

You can use the dubugging API for this. That is, in WinDbg + SOS :



    !DumpHeap -type System.String -min 20000 

      

+5


source


I don't recommend this, but one way to keep track of all instances of your shape is to do the following:

public abstract class Shape
{
    private static readonly List<WeakReference<Shape>> allShapes = new List<WeakReference<Shape>>();

    protected Shape()
    {
        allShapes.Add(new WeakReference<Shape>(this));
    }
}

      



If you need to do this, you might be solving your problem in the wrong way .

Thanks to Vyrx for suggestions WeakReference

for solving garbage collection problems.

+2


source







All Articles