Search code examples
c#collectionbase

How can I get a collection's parent object?


In C#, if I have an object that has a collection, is it possible to retrieve the object that contains the collection?

Here is an example:

public class TestObject
{
    public string name { get; set; }
    public TestObjectCollection testObjects{ get; set; } 
}

The TestObjectCollection collection inherits from CollectionBase and is a collection of TestObjects.

Here is an example implementation:

  • A TestObject is created with a name of "Test1"
  • The TestObject with the name of "Test1" has a TestObjectCollection with a TestObject with a name of "Test2"

If I have the TestObject with the name of "Test2", how can I get the TestObject with the name of "Test1"

Thanks


Solution

  • The only way to do this is to keep a reference to the parent in the child object. You can do this while creating the child object:

    this.testObjects = new TestObjectCollection(this);
    

    Then in TestObjectCollection's constructor:

    public TestObject ParentObject { get; set; }
    
    public TestObjectCollection(TestObject parent)
    {
        ParentObject = parent;
        ...
    }