What are circular references in C#?
The circular reference problem in C# causes a lock condition in two independent components/classes. This problem occurs when two or more parts of the program depend upon each other, making their resources unusable.
Example
Let's see how this circular reference problem arises through an example:
public class Pet{Dog petName;}public class Dog{Pet petName;}class HelloWorld{static void Main(){Dog tom = new Dog();System.Console.WriteLine("Hello, World!");}}
Explanation
Line 1–6: We have a
publicclasscalledPetand anotherclassnamedDog. The principle of composition can be seen in both classes asPethas a data memberpetnameof typeDogandDoghas a data memberdognameof typePet. Presence of circular reference problem.
Solution
The introduction of an interface can solve this problem:
public interface Ibridge{}public class Pet{Ibridge interface_common;}public class Dog:Ibridge{Pet petName;}class HelloWorld{static void Main(){Dog tom = new Dog();tom.setDogName("Tim");System.Console.WriteLine("Hello, World!");}}
As an interface is introduced, now the classes do not depend directly on each other and have a shared resource that they can utilize to avoid the circular reference problem.
The dependency graph shows that Dog now depends upon Pet and Ibridge. Meanwhile, Pet also depends on Ibridge. This breaks the circular dependency and resolves the lock condition.
Conclusion
Circular references are logical errors that can obstruct data flow within a program. By introducing interfaces, we can avoid this error in our code.
Free Resources