Glossary / Inheritance
Inheritance
Inheritance lets a class derive from one base class, reuse and specialize its behavior, and participate in runtime polymorphism. C# supports single class inheritance and multiple interface implementation; inheritance is most effective for stable “is-a” relationships with substitutable behavior, not merely code reuse.
Base and derived types
A derived class inherits accessible members and can add members, hide members with new, or override virtual/abstract members. A base constructor runs as part of derived construction. A class may be abstract to prevent direct instantiation and require derived implementations, or sealed to prevent further derivation. Constructors and private members are not inherited as ordinary accessible members.
Inheritance creates behavioral contracts: derived objects should be usable where the base is expected. Violations of invariants or surprising overrides break substitutability. Public/protected virtual members are extension points that constrain future base changes. Static members are not polymorphically overridden; they can be hidden.
Design guidance
Favor composition when behavior varies independently or the relationship is not truly subtype substitution. Keep hierarchies shallow and base classes focused. Make classes sealed by default when extensibility is not intended; use interfaces for capabilities across unrelated types. Test base contracts against derived implementations.
Interview questions
- Can a class inherit from two classes? No; it can inherit one class and implement multiple interfaces.
- What is
newvsoverride?newhides a member by compile-time lookup;overrideparticipates in virtual dispatch. - Why seal a class? To prohibit extension and preserve implementation freedom.
- When composition over inheritance? When behavior is orthogonal, replaceable, or does not satisfy substitutability.
- What is the Liskov concern? A subtype should preserve expectations/invariants of the base contract.