What is inheritance in C#

Inheritance in C# is a fundamental object-oriented programming concept that allows a class (called a child or derived class) to inherit fields and methods from another class (called a parent or base class). This mechanism promotes code reusability and establishes a hierarchical relationship between classes.

In C#, inheritance can take several forms, including single inheritance (where a class inherits from one base class) and multiple inheritance (though C# supports multiple inheritance through interfaces).

When a class inherits from another class, it can use the members (attributes and methods) of the base class as if they are defined in the derived class. This allows for the creation of new classes that have more specific behaviors based on the base class.

Here's a simple example of inheritance in C#:

// Base class class Animal { public void Speak() { Console.WriteLine("Animal speaks"); } } // Derived class class Dog : Animal { public void Bark() { Console.WriteLine("Dog barks"); } } // Usage class Program { static void Main(string[] args) { Dog myDog = new Dog(); myDog.Speak(); // Inherited method myDog.Bark(); // Local method } }

C# inheritance object-oriented programming derived class base class code reuse