Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collections and object initializers in C#

Tags:

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>() },
            },
        }
    }
});  
like image 500
Jay Double Avatar asked Feb 25 '26 20:02

Jay Double


2 Answers

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;
}
like image 150
Dzienny Avatar answered Feb 28 '26 08:02

Dzienny


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.

like image 35
Lasse V. Karlsen Avatar answered Feb 28 '26 10:02

Lasse V. Karlsen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!