I am developing a C# application and have an Employee class and an Organisation class.
An Employee object has an Organisation as an internal member and an Organisation object has an Employee member to indicate the Org leader.
Will there be any problems with this setup that can lead to an infinite circular instantiations?
Edit:
I just tried it running the code and there seems to be a problem. The employee object instantiates an Organisation object and an Organisation object tries to instantiate an employee object. They both connect to a database to fill in their details
This keeps happening until my SQL server runs out of connections. Is there any alternative to what I am doing?
Reference types are
nullby 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:
You can break a cycle like this by instantiating the instance of the other object outside of the constructor. For example, on first access:
You’ll still have to be careful that
class Adoesn’t access it’s ownthis.Bproperty 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:
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.