Search code examples
c#reflectionenumerate

Enumerating all instances of a type during runtime?


Solved.

I was wondering if anyone knows if it's possible to get all instantiated types of a specific type during runtime?

Let's say I want to Enumerate all instantiated objects of the type Foo.

public class Foo {}

var foo1 = new Foo();
Foo foo2 = new Foo();

IEnumerable<Foo> foos = GetObjects<Foo>(); 
//foos should contain foo1 and foo2

If there isn't a straight forward way of doing this, then I could just make a base type that subscribes its self on construction to some static service, and then do the look up that way... But I feel like this must already be implemented for the GC to work.


I would give most of you correct answer if I could, but since I couldn't I gave it to the first person to answer.


Solution

  • Answered over on the MSDN forums: http://social.msdn.microsoft.com/Forums/vstudio/en-US/f9e984e3-a47b-42b0-b9bd-1f1c55e4de96/getting-all-running-instances-of-a-specific-class-type-using-reflection?forum=netfxbcl

    Not possible :(

    Though they at least give you an idea of creating a static List to hold all references of the type (provided its your type of course) that you add to at creation time.