C# Inheritance

Inheritance is a fundamental feature of object-oriented programming that allows classes to inherit properties and behaviors from their parent classes. In C#, inheritance is implemented through the use of a base class and a derived class.

Types of Inheritance

There are five types of inheritance in C#:

  1. Single Inheritance: A derived class that inherits from a single base class.
  2. Multilevel Inheritance: A derived class that inherits from a base class, which itself inherits from another base class.
  3. Hierarchical Inheritance: Multiple derived classes that inherit from a single base class.
  4. Multiple Inheritance: A derived class that inherits from multiple base classes. However, C# doesn't support multiple inheritance in the traditional sense, but it can be achieved through interfaces.
  5. Hybrid Inheritance: A combination of any two or more types of inheritance.

Creating a Base Class

A base class is the class that is being inherited from. To create a base class in C#, we simply create a class with the desired properties and behaviors.

1public class Animal 2{ 3 public string Name { get; set; } 4 public int Age { get; set; } 5 6 public void Eat() 7 { 8 Console.WriteLine("The animal is eating."); 9 } 10}

Creating a Derived Class

A derived class is the class that inherits from the base class. To create a derived class in C#, we use the : symbol and the name of the base class.

1public class Dog : Animal 2{ 3 public void Bark() 4 { 5 Console.WriteLine("The dog is barking."); 6 } 7}

In the above example, the Dog class inherits from the Animal class.

Accessing Inherited Members

The derived class inherits all the public and protected members of the base class. To access the inherited members in the derived class, we use the base keyword.

1public class Dog : Animal 2{ 3 public void Bark() 4 { 5 Console.WriteLine("The dog is barking."); 6 } 7 8 public void ShowAge() 9 { 10 Console.WriteLine($"The dog's age is {base.Age}."); 11 } 12}

In the above example, we use the base keyword to access the Age property of the Animal base class.

Overriding Inherited Members

A derived class can override the members of the base class using the override keyword.

1public class Dog : Animal 2{ 3 public void Bark() 4 { 5 Console.WriteLine("The dog is barking."); 6 } 7 8 public override void Eat() 9 { 10 Console.WriteLine("The dog is eating."); 11 } 12}

In the above example, the Eat method of the Animal base class is overridden in the Dog derived class.