I would like to implement a method that receives a root object and returns a list containing references to all objects that can be reached starting from the root object. Its signature would be something like this:
static List<object> EnumerateObjectsInRange(object root);
I’m thinking about using GetProperties() to retrieve an array of PropertyInfo objects, then get these properties’ values using GetValue() and finally call GetProperties() again for each value and repeat this procedure until the entire object graph has been visited, but I’m not sure if this is the best approach.
Any suggestions?
EDIT:
I can think of two definitions for reachable:
- All objects the owner of the root object would be able to access (public available objects).
- All public and private objects referenced by the object graph to which the root object belongs.
The first definition is enough for my purposes.
You definitely need fields, not properties. Objects keep other objects alive via fields, never via properties. You don’t need to special-case lists because they contain an internal array which you will find using GetFields. You need to special-case arrays, however.
Btw, I have implemented this algorithm and found it to be working and useful.