Basic Inheritance (:) Syntax
Part of the Object Oriented Programming section of Coddy's C# journey — lesson 19 of 70.
Inheritance allows a class to acquire the properties and methods of another class. Instead of rewriting the same code, you create a base class (parent) with shared functionality, then create derived classes (children) that inherit from it.
In C#, you use the colon : symbol to indicate inheritance:
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!");
}
}The Dog class inherits everything from Animal. It has access to the Name property and Eat() method without declaring them again, plus it adds its own Bark() method:
Dog myDog = new Dog();
myDog.Name = "Buddy";
myDog.Eat(); // Output: Buddy is eating.
myDog.Bark(); // Output: Buddy says Woof!C# supports single inheritance only, meaning a class can inherit from just one base class. However, you can build inheritance chains where a derived class becomes the base for another class. This creates a hierarchy that models real-world relationships while keeping your code organized and reusable.
Challenge
EasyLet's build a vehicle hierarchy that demonstrates how inheritance allows derived classes to share functionality from a base class while adding their own unique behaviors.
You'll create three files to organize your code:
Vehicle.cs: Define aVehicleclass in theTransportnamespace. This will be your base class that all vehicles share. It should have aBrandproperty (string) and aYearproperty (int), along with a methodStartEngine()that prints"{Brand} engine started."Car.cs: Define aCarclass in theTransportnamespace that inherits fromVehicle. The car adds its own propertyNumberOfDoors(int) and a methodHonk()that prints"{Brand} goes Beep Beep!"Program.cs: In your main file, create aCarinstance using input values. Set its properties (including the inherited ones), then demonstrate that the car can use both its own methods and the methods it inherited fromVehicle.
You will receive three inputs:
- Brand name
- Year
- Number of doors
Print the car's information and demonstrate its capabilities in this format:
Car: {Brand} ({Year})
Doors: {NumberOfDoors}
{StartEngine output}
{Honk output}For example, if the inputs are Toyota, 2022, and 4, the output should be:
Car: Toyota (2022)
Doors: 4
Toyota engine started.
Toyota goes Beep Beep!Notice how your Car can access the Brand property and StartEngine() method even though they're defined in Vehicle. That's the power of inheritance - the derived class automatically gets everything from its base class!
Cheat sheet
Inheritance allows a class to acquire properties and methods from another class using the colon : symbol:
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!");
}
}The derived class (Dog) inherits all properties and methods from the base class (Animal) and can add its own:
Dog myDog = new Dog();
myDog.Name = "Buddy";
myDog.Eat(); // Inherited method
myDog.Bark(); // Own methodC# supports single inheritance only - a class can inherit from just one base class. However, you can create inheritance chains to build hierarchies.
Try it yourself
using System;
using Transport;
class Program
{
public static void Main(string[] args)
{
// Read input
string brand = Console.ReadLine();
int year = Convert.ToInt32(Console.ReadLine());
int doors = Convert.ToInt32(Console.ReadLine());
// TODO: Create a Car instance
// TODO: Set the car's properties (Brand, Year, NumberOfDoors)
// TODO: Print the car's information in the required format:
// Car: {Brand} ({Year})
// Doors: {NumberOfDoors}
// Then call StartEngine() and Honk()
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesNamespaces & DirectivesIntro to Classes & ObjectsThe 'this' KeywordMethods and ParametersFields vs PropertiesConstructorsObject InitializersRecap - Simple Calculator4Inheritance
Basic Inheritance (:) SyntaxThe 'base' KeywordVirtual & Override KeywordsSealed ClassesThe 'object' Base ClassRecap - Employee Hierarchy7Advanced Features
Operator OverloadingIndexers (this[])ToString() OverrideExtension MethodsRecap - Custom List2Properties & Static Members
Auto-Implemented PropertiesRead/Write-Only PropertiesStatic Fields & MethodsStatic ClassesExpression-Bodied Members5Polymorphism & Interfaces
Compile vs Runtime PolyInterface vs Abstract ClassMultiple InterfacesExplicit InterfacesUpcasting & DowncastingRecap - Shape Calculator