Explain the concept of inheritance in C# and provide an example.
Explain the concept of inheritance in C# and provide an example.
19702-Jul-2023
Updated on 04-Jul-2023
Home / DeveloperSection / Forums / Explain the concept of inheritance in C# and provide an example.
Explain the concept of inheritance in C# and provide an example.
Aryan Kumar
04-Jul-2023Sure. In C#, inheritance is the ability for a class to inherit the properties and methods of another class. The class that inherits from another class is called the derived class, and the class that is being inherited from is called the base class.
For example, the following code defines a class
Animal
and a derived classDog
:C#
The
Dog
class inherits from theAnimal
class. This means that theDog
class has all of the properties and methods of theAnimal
class, plus any additional properties and methods that are defined in theDog
class.In this example, the
Dog
class does not define any additional properties or methods. However, it could define additional properties or methods, such as a method calledBark()
.When an object of type
Dog
is created, it will also have all of the properties and methods of theAnimal
class. This means that an object of typeDog
can call theSpeak()
method, even though theSpeak()
method is defined in theAnimal
class.Inheritance is a powerful feature that can be used to improve code reuse and code readability. It can also be used to implement polymorphism.
Here are some of the benefits of using inheritance: