Will there be any problems with this setup that can lead to an infinite circular instantiations?
Reference types are null
by default. Unless you instantiate a new instance and assign it to that variable, then no code is called for that type.
Do each of the constructors construct an instance of the other object? Is it possible that they could in the future (possibly on accident)? If so, then yes, you can hit the scenario you are talking about:
class A
{
public A()
{
this.B = new B();
}
public B B;
}
class B
{
public A A = new A(); // This is the same as instantiating the object in the ctor
}
// ...
A obj = new A(); // This calls new B, which calls new A, repeat ad infinitum
You can break a cycle like this by instantiating the instance of the other object outside of the constructor. For example, on first access:
class A
{
public A()
{
}
public B B
{
get
{
if(b == null)
b = new B();
return b;
}
}
private B b;
}
class B
{
public B()
{
}
public A A
{
get
{
if(a == null)
a = new A();
return a;
}
}
private A a;
}
// ...
A obj = new A(); // new B doesn't get called yet
obj.B.Something(); // ... Now it does...
You'll still have to be careful that class A
doesn't access it's own this.B
property inside its constructor, and vice-versa. You can access these properties in methods all you want, though, as long as those methods aren't called inside the constructor.
Another option is to do dependency injection. This is where you pass a dependency to an object, instead of letting it instantiate the object itself:
class A
{
public A(B b)
{
this.B = b;
}
public B B;
}
class B
{
public B(A a)
{
this.A = a;
}
public A A;
}
// ...
A someA = new A(
new B(
null)); // You have to break the cycle somewhere...
someA.B.A = someA;
// or ...
class ABFactory
{
public static A CreateA(/* options for a */, /* options for b */)
{
A result = new A(
new B(
null));
result.B.A = result;
return result;
}
}
Note that dependency injection wasn't invented to solve this problem, but it would work in this scenario. With it, you could rest easy, knowing that you would never hit this issue again.