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>() },
},
}
}
});
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;
}
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.
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