Here's a program based on C# inheritance with an explanation:
using System; namespace InheritanceExample { class Animal { public void Eat() { Console.WriteLine("Eating..."); } } class Dog : Animal { public void Bark() { Console.WriteLine("Barking..."); } } class Program { static void Main(string[] args) { Dog myDog = new Dog(); myDog.Eat(); // This method is inherited from the Animal class myDog.Bark(); // This method is specific to the Dog class } } }In this program, we have a base class called Animal and a derived class called Dog which inherits from the Animal class using the : symbol.
The Animal class has a public method called Eat() which simply writes "Eating..." to the console.
The Dog class has a public method called Bark() which writes "Barking..." to the console.
In the Main() method of the Program class, we create a new instance of the Dog class called myDog. We then call the Eat() method which is inherited from the Animal class, and the Bark() method which is specific to the Dog class.
When we run the program, we get the following output:
This program demonstrates how we can use inheritance in C# to reuse code and define more specific classes based on more general ones. The Dog class is able to use the Eat() method defined in the Animal class because it inherits from it. This allows us to avoid duplicating code and make our programs more efficient and maintainable.
Eating... Barking...