If I have a parent, child, grandchild set of classes, where the grandchild require's it's parent as a constructor parameter, is there any way to still be able to use a nested Object Initializers declaration?
For example, consider Invoice Header, Invoice Line, Invoice Line breakdown:
public class InvoiceHeaderModel
{
public List<InvoiceLineModel> InvoiceLineModels { get; set; }
}
public class InvoiceLineModel
{
public List<InvoiceLineBreakdown> InvoiceLineBreakdowns { get; set; }
}
public class InvoiceLineBreakdown
{
public InvoiceLineBreakdown(InvoiceLineModel parentInvoiceLine)
{
_parentInvoiceLine = parentInvoiceLine;
}
private InvoiceLineModel _parentInvoiceLine;
}
What I'd like to be able to do is this:
public InvoiceHeaderModel BuildAnInvoice()
{
return new InvoiceHeaderModel
{
InvoiceLineModels = new List<InvoiceLineModel>
{
new InvoiceLineModel
{
InvoiceLineBreakdowns = new List<InvoiceLineBreakdown>
{
new InvoiceLineBreakdown(/* Need to reference the anonymous outer InvoiceLineModel*/),
new InvoiceLineBreakdown()
}
}
}
};
}
But I can't, as the InvoiceLineBreakdown
's constructor needs a reference to the anonymous InvoiceLineModel
that contains it.
I appreciate there are good arguments for not referencing parents from children, but is there any way to achieve the nested declaration above using Object Initializers], or do I just have to explicitly declare all the objects and then compose the Invoice Header afterwards?