Skip to content

Inheritance

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).

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 Animal
Console.WriteLine(generic.Speak()); // "Fido barks" -- still calls Dog's override (polymorphism)

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 Dog
  1. How many classes can a C# class directly inherit from?

    AnswerExactly one β€” C# supports single inheritance for classes (though a class can implement multiple interfaces).
  2. What keyword must a base class method have for a derived class to properly override it?

    Answervirtual (or abstract) β€” without it, a derived class's same-named method hides rather than overrides the base version.
  3. What’s the practical difference between β€œhiding” a method with new and truly β€œoverriding” it with override?

    AnswerWith 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.