I am aware of the fact that circular dependency with respect to inheritance doesn't have any practical use but I found this concept interesting.
Inheritance
Inheritance is an important pillar of Object-Oriented Programming. It is the mechanism by which one class is allowed to inherit the features (fields and methods) of another class.
Circular Dependency
With respect to inheritance, the circular dependency is where Class A inherits from Class B and Class B inherits from Class A (directly or indirectly).
Example 1
In the below example, Class A inherits from Class C while Class C inherits from Class B and Class B inherits from Class A.
- namespace TestInheritanceDependancy
- {
- class A : C
- {
- }
- class C : B
- {
- }
- class B : A
- {
- }
- }
The above program will give an error like below.
Circular base class dependency involving 'TestInheritanceDependancy.B' and 'TestInheritanceDependancy.A'
Example 2
First of all, I will define what a Nested class is. In C#, we can define a class within another class. Such types of classes are known as nested classes. This allows the logically grouped classes that are only used in one place; thus increasing the use of encapsulation.
In the below example, Class B is a nested class of Class A and Class A inherits the inner class B.
- public class A : A.B
- {
- public class B { }
- }
The above program will give an error too.
Circular base class dependency involving 'A' and 'A.B'
Conclusion
The above examples prove that circular dependency is not allowed in C# inheritance.