I have a feeling that this is a code smell, and I could be doing this better, and if that is the case please point it out.
class main
{
void main()
{
object A
object B
A = new SystemA(ref B)
B = new SystemB(ref A)
}
}
class SystemA
{
SystemB B;
public SystemA (ref B)
{
this.B = B;
}
}
class SystemB
{
SystemA A;
public SystemA (ref A)
{
this.A = A;
}
}
Basically I need to initialize two classes with references to each other.
This doesn’t work and generates a null reference exception for the class fields in the two child classes when they are later accessed after initialization.
I realize I could probably set these after initialization, but this adds a touch more bloat that I would like to avoid, since I view these assignments as initialization actions.
If you gave code which actually compiled, I suspect it would just end up with
SystemAstoring a reference tonull– because that’s the value ofBwhen you constructA.Having two classes which need a reference to each other is definitely a code smell, but you simply can’t make them both refer to each other, unless one of them constructs the other and passes in “this”, e.g.
Now if you need access to both values afterwards, you could either put a property in one of them giving access to the other, or (and this is really nasty) use an
outparameter in the constructor:Then call it as:
Please don’t do this though.
thisescape a constructor anyway