Inheritance
Inheritance
Section titled βInheritanceβWhat it means
Section titled βWhat it meansβInheritance lets a class (the derived or subclass) reuse and extend the members of another class (the base class), expressed with a colon: class Dog : Animal. The derived class automatically gets all the base classβs non-private members, and can add new members or override virtual ones. C# only allows single inheritance from one base class (unlike interfaces, which support multiple).
Examples
Section titled βExamplesβpublic class Animal{ public string Name { get; set; } public virtual string Speak() => $"{Name} makes a sound";}
public class Dog : Animal{ public override string Speak() => $"{Name} barks"; // overrides the base behavior}
public class Puppy : Dog{ public string PlayFetch() => $"{Name} chases the ball"; // new member, only on Puppy}
var dog = new Dog { Name = "Fido" };Console.WriteLine(dog.Speak()); // "Fido barks"
Animal generic = dog; // upcasting -- a Dog IS an AnimalConsole.WriteLine(generic.Speak()); // "Fido barks" -- still calls Dog's override (polymorphism)Common mistake
Section titled βCommon mistakeβForgetting virtual on a base class method thatβs meant to be overridden β without it, a derived classβs same-named method with new (or accidentally without any keyword) hides the base method instead of truly overriding it, which behaves inconsistently depending on the static type of the reference.
public class Animal{ public string Speak() => "..."; // NOT virtual}
public class Dog : Animal{ public new string Speak() => "Woof!"; // hides, doesn't override}
Animal a = new Dog();Console.WriteLine(a.Speak()); // "..." -- calls Animal's version! Not what most people expect.
Dog d = new Dog();Console.WriteLine(d.Speak()); // "Woof!" -- calls Dog's version, since the static type is DogQuick practice
Section titled βQuick practiceβ-
How many classes can a C# class directly inherit from?
Answer
Exactly one β C# supports single inheritance for classes (though a class can implement multiple interfaces). -
What keyword must a base class method have for a derived class to properly
overrideit?Answer
virtual(orabstract) β without it, a derived class's same-named method hides rather than overrides the base version. -
Whatβs the practical difference between βhidingβ a method with
newand truly βoverridingβ it withoverride?Answer
With overriding, the derived class's version always runs, even when called through a base-class-typed reference (true polymorphism); with hiding, which method runs depends on the *static* type of the reference at compile time, not the actual object type.