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
You can't do this because an instance of Parent has not been created yet. If child requires an instance of Parent in it's constructor you must create one. Create an instance of Parent first, then Child passing in the parent to the Constructor, and then assign the instance of child to the property on Parent.
var parent = new Parent
{
Name = "Parent",
//More here...
};
var child = new Child(parent);
parent.Child = child;
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.
No, because the reference starts referencing the allocated object after the constructor's execution has finished.