Let\'s say I have a parent/child-relationship ob objects and try to create a parent object inline (I\'m not really sure that\'s the right word). Is it possible to reference
The only way round this would be for the Parent
constructor to call the Child
constructor itself and pass in this
. Your object initializer (which is what I assume you're trying to do) could then set other properties on the child:
public class Parent
{
public Child Child { get; private set; }
public string Name { get; set; }
public Parent()
{
Child = new Child(this);
}
}
public class Child
{
private readonly Parent parent;
public string Name { get; set; }
public Child(Parent parent)
{
this.parent = parent;
}
}
Then:
Parent parent = new Parent
{
Name = "Parent name",
// Sets the Name property on the existing Child
Child = { Name = "Child name" }
};
I would try to avoid this sort of relationship though - it can get increasingly tricky as time goes on.