Sending reference of object before its construction

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?


My question is, in the First() constructor, isnt it bad that we are sending a reference of class First() BEFORE it is fully constructed?

Somewhat. It can be a problem, certainly.

If the Second constructor just holds onto a reference for later use, that's not too bad. If, on the other hand, the Second constructor calls back into First:

public Second(First f)
{
    f.DoSomethingUsingState();
}

... 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 First then 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, readonly fields 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...


If you encounter this pattern, you might check if it can be refactored into this instead:

public class First()
{
      private Second _second;

      public First()
      {
          _second = new Second(this);
          // Doing some other initialization stuff,
      }

      private class Second
      {
          public Second(First f)
          {
          }
      }
}

Passing the dependency into the constructor implies a kind of tight coupling between the two classes, as First has to trust that Second knows what it is doing and won't try to rely on the uninitialized state of First. This kind of strong coupling is more appropriate when Second is a private nested subclass (and hence a clear implementation detail) or possibly when it's an internal class.


The answer is, it depends. Generally, though, this would be considered a bad idea due to the potential consequences.

More specifically, though, as long as Second doesn't actually use anything from First before it is constructed, then you should be okay. If you can't guarantee that somehow though, you could definitely run into problems.