C# Inheritance
3 min readDec 21, 2022
Inheritance is a fundamental concept in object-oriented programming that allows one class to inherit the properties and methods of another class. This can help you to create more efficient and reusable code, as you can create a base class that defines shared behavior and characteristics, and then use inheritance to create more specialized subclasses that are based on the base class.
Here’s an example of how inheritance works in C#:
// Define the base class.
public class Animal
{
// Properties of the base class.
public string Name { get; set; }
public int Age { get; set; }
// Method of the base class.
public void MakeNoise()
{
Console.WriteLine("Making noise...");
}
}
// Define the subclass.
public class Dog : Animal
{
// Property of the subclass.
public string Breed { get; set; }
// Method of the subclass.
public void Bark()
{
Console.WriteLine("Woof!");
}
}
// Create an instance of the subclass.
Dog myDog = new Dog();
// Set the properties of the subclass.
myDog.Name = "Buddy";
myDog.Age = 3;
myDog.Breed = "Labrador";
// Call the method of the base class.
myDog.MakeNoise(); // Outputs "Making noise..."
// Call the method of the subclass.
myDog.Bark(); // Outputs "Woof!"
In this example, we have a base class called Animal
that has two properties (Name
and Age
) and a method (MakeNoise
). We…