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
TestObjectis created with a name of"Test1" - The
TestObjectwith the name of"Test1"has aTestObjectCollectionwith aTestObjectwith 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
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:
Then in TestObjectCollection's constructor: