Jay Double
Jay Double

Reputation: 57

Collections and object initializers in C#

I need to store reference to a parent object in hierarchical dataset shown below. Is it even possible using an object initializer? Is there any keyword which refers to 'parent' initializer or do I have to do this the classic way - declare the parent object first?

(I have no idea what to write in between '?' characters)

Scenarios.Add(new Scenario()
{
    scenarioNumber = Scenarios.Count,
    scenarioDescription = "Example scenario",
    Steps = new BindingList<Step>()
    {
        new Step(){ parent = ?Scenario?, stepNumber = 1, subSteps = new BindingList<Step>() },
        new Step(){ parent = ?Scenario?, stepNumber = 2, subSteps = new BindingList<Step>() },
        new Step(){ parent = ?Scenario?, stepNumber = 3,
            subSteps = new BindingList<Step>()
            {
                new Step() { parent = ?Step?, stepNumber = 1, subSteps = new BindingList<Step>() },
                new Step() { parent = ?Step?, stepNumber = 2, subSteps = new BindingList<Step>() },
            },
        }
    }
});  

Upvotes: 3

Views: 66

Answers (3)

Dzienny
Dzienny

Reputation: 3417

The object initializer construct does not allow this.

You can use a static factory method instead, for example:

static Scenario Create(int scenarioNumber, string scenarioDescription, BindingList<Step> steps)
{
    var scenario = new Scenario()
    {
        scenarioNumber = scenarioNumber,
        scenarioDescription = scenarioDescription,
    };
    foreach (var step in steps)
    {
        step.parent = scenario;
    }
    scenario.Steps = steps;
    return scenario;
}

Upvotes: 3

AdricoM
AdricoM

Reputation: 579

For me it will not be possible to avoid parent creation and then affecting it : as far as I know, object initializer is doing its work as if it were inside the constructor, so your parent Scenario instance is not yet created when you initialize its inside collection

And sorry if I'm mistaken

Upvotes: 0

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391286

No, it isn't possible.

You will have to declare variables to hold the parent objects and add them manually, one at a time. The initializer syntax cannot help you here.

Upvotes: 1

Related Questions