How can I avoid passing a reference to a parent object when constructing a new instance of a class?

c#, class, constructor, object

Solution

Presumably `Content` needs a `Master` ? Actually, constructors are a fairly good way of managing this, but if that is a problem, you could also do something like:

internal class Content {
    internal void SetMaster(Master master) {this.master = master; }
    //...
}
internal class Master {
    internal void SetContent(Content content) {
        if(content == null) throw new ArgumentNullException("content");
        // maybe handle double-calls...
        this.content = content;
        content.SetMaster(this);
    }
}
...
Master M = new Master();
M.SetContent(new Content());

or have `Master` create the `Content` by default. Frankly, though, I'd leave it "as is" until there is an actual "this is a problem".

Problem

I have two classes defined as follows. First one: ``` internal class Content { internal Content(Master master) { // code omitted } // code omitted } ``` second one: ``` public class Master { internal Content content { get; set; } internal Master() { // code omitted } // code omitted } ``` Exposing the Content Class as property of the Master I need to do something like this: ``` Master M = new Master(); M.content = new Content(M); ``` Is there a way to do not pass the Master (M) in the Content Consctructor?

Original source