Chiritescu Adrian Chiritescu Adrian - 1 year ago 54
C# Question

How to get the n-th reference of an object declared inside the same object type?

I have a problem with an object that has the same object inside and this object has inside another object and so on, for exameple:

class SomeObject
SomeObject obj;

var obj= new SomeObject{ };
obj.obj= new SomeObject{ };
obj.obj.obj= new SomeObject{ };

My question is how do I find the latest object, I could use this:

if(obj.obj== null)
obj.obj= new SomeObject{ }; //assign it a new object

but how to do this automatically ? How to loop through all object if the respective object doesn't implements the IEnumerable interface ? And also how do I get the reference of the latest object uninitialized so I can assign it a new object without having to do:

obj.obj.obj.obj = new SomeObject{ };

Answer Source

There is the concept of recursion: MSDN You can declare an method and make recursive calls until you find what you want.

static void AddObject(SomeObject currentObject, SomeObject child) {
  if(currentObject == null) return; 
  else if(currentObject.obj != null) AddObject(currentObject.obj, child);
  else currentObject.obj = child;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download