Recursive Type Inheritance¶
What does this mean ?¶
A C# class cannot directly or indirectly inherit from itself. The compiler reports a circular base-class dependency, such as CS0146. This differs from a tree containing child nodes of its own type or a generic base parameterized by a derived type; those patterns are not automatically invalid.
What can happen ?¶
A direct base-class cycle prevents a successful build. Do not describe every recursive generic declaration as code that compiles but necessarily crashes when instantiated. Complex constructed types require analysis of the exact declaration and target runtime. A linter finding alone does not prove an exploitable vulnerability.
Recommendation¶
Use inheritance to express a one-way specialization relationship. Move common behavior into an independent base, or use fields and collections to express containment. Avoid introducing inheritance just to reuse a few methods; a composed helper often represents that relationship more clearly.
Sample Code¶
Invalid circular dependency:
public class Folder : FileEntry { }
public class FileEntry : Folder { }
Independent specializations of a common base:
public abstract class Entry { }
public class Folder : Entry { }
public class FileEntry : Entry { }
Regression test: compile the invalid example and expect a circular dependency diagnostic. Compile the replacement, construct both derived types, and use each through an Entry reference. For recursive data structures, separately test traversal limits and cycle handling where untrusted input can create large graphs; fixing a type hierarchy does not bound runtime work.
References¶
- C# inheritance
- Related: resource exhaustion.