You'll probably need to work backward: step3
first, then step2
that addresses step3
in its constructor, etc.
How to reference an object that hasn't yet been instantiated
-
11-07-2023 - |
Question
I'm trying to model a flow chart in C#. I'll simplify the classes a bit, but the basic idea is that a given Step
points to another Step
. What I want to do is set up the linkage between everything in one place in code. For example, I want step1
to point to step2
which points to step3
class Step
{
Step nextStep;
// Constructor
public Step(Step nextStep) { this.nextStep = nextStep; }
}
class Chart
{
private readonly Step step1;
private readonly Step step2;
private readonly Step step3;
public Chart()
{
step1 = new Step(step2);
step2 = new Step(step3);
step3 = new Step(null);
}
}
static void main()
{
Chart myChart = new Chart();
}
This compiles fine, but if the nextStep object hasn't been instantiated yet, the reference is lost upon instantiation.
In this example, step1
's constructor is passed step2
, which is null
at that point. I was hoping that when step2
is instantiated, the reference within step1
would properly point to the newly created step2
, but it doesn't.
It's looking like I need to first instantiate ALL the objects, then go back and set the links via a setter or some such. Is that the proper way? Or can it be done in the constructor as I tried?
Solution
OTHER TIPS
You need to create an actual object which doesn't point to anything else.
step3 = new Step(null);
From there, set your steps in reverse order, until you reach the first step.
step2 = new Step(step3);
step1 = new Step(step2);
If you want to do this in the constructor, the object will have to be created first. One way of using dependency injection would be to pass in the parent and assign the new step to be the parent's next step.
Example:
class Step
{
private Step nextStep;
public Step() {}
public Step(Step parent)
{
parent.nextStep = this;
}
}
static void main()
{
Step step1, step2, step3;
step1 = new Step();
step2 = new Step(step1);
step3 = new Step(step2);
}