3

Suppose you have a class Shape. Assume Shape has been instantiated as Circle, Square, and Triangle. Is there a way at runtime to get a list of the names of the Shape objects and then to iterate over those objects?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
  • 3
    do you mean variable names? – thumbmunkeys Aug 15 '14 at 19:05
  • 1
    If you need to track object references (i.e. instansiations), why not use something like `List`? (in your case `List` which could contain Circle, Square, Triangle) – Fred Aug 15 '14 at 19:06
  • You can try GetType(); – Benoit Aug 15 '14 at 19:07
  • 2
    Do you ask how to find all derived types, or how to find all instantiated objects of such types? – Eugene Podskal Aug 15 '14 at 19:07
  • You mean ".NET Reflection", not "C# Reflection". – John Saunders Aug 15 '14 at 19:08
  • 1
    If you mean how to find all derived types - http://stackoverflow.com/questions/5411694/get-all-inherited-classes-of-an-abstract-class. If you mean how to find all instantiated objects of such types - http://stackoverflow.com/questions/2935461/how-to-get-or-kill-all-instances-from-certain-class. – Eugene Podskal Aug 15 '14 at 19:11

2 Answers2

5

There is no way to use reflection to obtain list of instantiated objects. Reflection can give information about type or interact with objects you have reference to, it does not let you find "all object of this type ever created".

You can use dubugging APIs to do that. I.e. in WinDbg + SOS:

    !DumpHeap -type System.String -min 20000 
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
2

I don't recommend this, but one way of tracking 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 may be solving your problem the wrong way.

Thanks to Vyrx for the WeakReference suggestion to solve garbage collection issues.

Community
  • 1
  • 1
Anthony
  • 9,451
  • 9
  • 45
  • 72