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?
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".
Why not use lazy initialisation idom?
public class Master
{
private Content _content;
internal Content content
{
get
{
if (_content == null)
{
_content = new Content(this);
}
return _content;
}
}
}
If Master
always has to have content
property set then create Content
member during construction:
public class Master
{
internal Content content
{
get; private set;
}
internal Master()
{
content = new Content(this);
}
}
You may also use mixed approach:
public class Master
{
internal Content content
{
get; private set;
}
internal Content GetOrCreateContent()
{
if (content == null)
{
content = new Content(this);
}
return content;
}
internal Master()
{
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With