I have seen the following code in one of our applications:
public class First()
{
private Second _second;
public First()
{
_second = new Second(this);
// Doing some other initialization stuff,
}
}
public class Second
{
public Second(First f)
{
}
}
In the First() constructor, isn’t it bad that we are sending a reference of class First() before it is fully constructed? I am thinking that the object is only fully constructed once the control logic leaves the constructor.
Or is this okay?
Somewhat. It can be a problem, certainly.
If the
Secondconstructor just holds onto a reference for later use, that’s not too bad. If, on the other hand, theSecondconstructor calls back intoFirst:… and the state hasn’t been set up yet, then that would of course be a Very Bad Thing. If you call a virtual method on
Firstthen it could be even worse – you could end up calling into some code which hasn’t even had a chance to run any of its constructor body yet (although its variable initializers will have been executed).In particular,
readonlyfields may be seen first with one value and then later with another…I blogged about this a while ago, which may provide some more information.
Of course, without doing this sort of thing, it’s pretty hard to create two mutually-referential immutable objects…