You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Inheritance and interfaces are core pillars of object-oriented programming in C#. They enable code reuse, polymorphism, and the design of flexible, extensible systems.
A class can inherit from a single base class:
public class Animal
{
public string Name { get; set; }
public void Eat()
{
Console.WriteLine($"{Name} is eating.");
}
}
public class Dog : Animal
{
public void Bark()
{
Console.WriteLine($"{Name} says: Woof!");
}
}
var dog = new Dog { Name = "Rex" };
dog.Eat(); // Inherited from Animal
dog.Bark(); // Defined in Dog
Important: C# supports single inheritance only — a class can inherit from one base class, but can implement multiple interfaces.
Use virtual and override for runtime polymorphism:
public class Shape
{
public virtual double Area() => 0;
public virtual string Describe() => "I am a shape.";
}
public class Circle : Shape
{
public double Radius { get; set; }
public override double Area() => Math.PI * Radius * Radius;
public override string Describe() => $"Circle with radius {Radius}";
}
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.