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?
Asked
Active
Viewed 414 times
3
-
3do you mean variable names? – thumbmunkeys Aug 15 '14 at 19:05
-
1If you need to track object references (i.e. instansiations), why not use something like `List
`? (in your case `List – Fred Aug 15 '14 at 19:06` which could contain Circle, Square, Triangle) -
You can try GetType(); – Benoit Aug 15 '14 at 19:07
-
2Do 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
-
1If 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 Answers
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.
-
3
-
`WeakReference` is not generic though. So you need `WeakReference` instead of `WeakReference
` – Sriram Sakthivel Aug 15 '14 at 19:19 -
Yes it is... [WeakReference
](http://msdn.microsoft.com/en-us/library/gg712738%28v=vs.110%29.aspx) - .NET 4.5 – Anthony Aug 15 '14 at 19:22