0

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?

tomRedox
  • 28,092
  • 24
  • 117
  • 154

1 Answers1

0

Use a variable reference.

Here is a complete example:

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        var ihm = new 
    {
        InvoiceLineModels = new List<Object>
        {
           new {
               Test = 1,
               //ihm = ihm Can't be used here until the declaration is completed nor can this be used.
           }
        }
    };
        //ihm is available here 
        Console.WriteLine(ihm.ToString());
    }
}

It seems you should separate the processes; load the children from the db and then add them to the list to be returned which can be stored in the ihm. Use the let syntax to achieve that same thing during query.

In summary. Wheres the POF for the allocation etc. Good luck

Jay
  • 3,276
  • 1
  • 28
  • 38