How to solve circular reference?

Viewed 59636

How do you solve circular reference problems like Class A has class B as one of its properties, while Class B has Class A as one of its properties?

How to do architect for those kind of problems?

If you take an example of NHibernate, there will be a parent-child relationship between objects.

How is it able to handle those parent child scenarios?

6 Answers

interfaces are a good idea however if your looking for a quicker solution than redoing the architecture of so many things try building one dll class library that holds all your data structures your main project holds your UI that needs that data and then any other dlls you want to add can access that data structures dll as well so they have all the info they need to run but still can be separate- this is called the tri force design pattern -

Circular reference occurs when two or more interdependent resources cause lock condition. This makes the resource unusable.

To handle the problem of circular references in C#, you should use garbage collection. It detects and collects circular references. The garbage collector begins with local and static and it marks each object that can be reached through their children.

Through this, you can handle the issues with circular references.

Let’s say the following classes is in circular reference. Here both of them depends on each other −

public class A
        {
            B Two;
        }
public class B
        {
            A one;
        }

To solve the issue, create an interface −

public interface myInterface {
}

public class A {
   myInterface Two;
}

public class B: myInterface {
   A one;
}
Related