Inheritance models is-a relationships: class Dog : Animal. Derived classes inherit members, can override behavior with virtual/override, and call base logic with base—similar to Java but C# supports single inheritance of classes only.
Basic inheritance
class Animal {
public virtual void Speak() => Console.WriteLine("...");
}
class Dog : Animal {
public override void Speak() => Console.WriteLine("woof");
}
All classes implicitly inherit object—every type has ToString, Equals, and GetHashCode.
Important interview questions and answers
- Q: Single vs multiple inheritance?
A: C# allows one base class; use interfaces for additional contracts—avoid diamond problems from C++ multiple inheritance. - Q: sealed classes?
A:sealedprevents further derivation—use when extension would break invariants.
Self-check
- What keyword calls a base constructor or method?
- Can a class extend two classes?
Pitfall: C# allows single class inheritance only—use interfaces for additional contracts instead of multiple base classes.
Interview prep
- Single vs multiple inheritance?
C# allows one base class; use interfaces for additional contracts—avoids diamond problems from C++ multiple inheritance.
- sealed classes?
sealedprevents further derivation—use when extension would break invariants.