Inheritance in C#
What is Inheritance in C#?
Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a class (derived class) to inherit fields and methods from another class (base class). This promotes code reusability and hierarchical relationships between classes.
Key Features of Inheritance
- Enables code reuse by allowing one class to inherit members from another.
- Promotes hierarchical class structures.
- Supports method overriding for customized behavior in derived classes.
- Facilitates polymorphism by allowing a derived class to be treated as its base class.
Example of Inheritance
The following example demonstrates how a derived class inherits properties and methods from a base class.
Example of Inheritance:
public class Animal
{
public void Eat()
{
Console.WriteLine("This animal is eating.");
}
}
// Derived class inheriting from Animal
public class Dog : Animal
{
public void Bark()
{
Console.WriteLine("Dog is barking.");
}
}
// Usage
Dog myDog = new Dog();
myDog.Eat(); // Inherited from Animal
myDog.Bark(); // Defined in Dog class
In this example, Dog
inherits from Animal
, gaining access to the Eat()
method while defining its own method, Bark()
.
Types of Inheritance in C#
C# supports different types of inheritance:
- Single Inheritance: A class inherits from one base class.
- Hierarchical Inheritance: Multiple derived classes inherit from a single base class.
- Multilevel Inheritance: A derived class becomes a base class for another class.
- Multiple Inheritance (via Interfaces): A class implements multiple interfaces.
Method Overriding in Inheritance
Inheritance allows derived classes to override methods from the base class to provide a specific implementation.
Example of Method Overriding:
public class Animal
{
public virtual void MakeSound()
{
Console.WriteLine("Animal makes a sound.");
}
}
public class Dog : Animal
{
public override void MakeSound()
{
Console.WriteLine("Dog barks.");
}
}
// Usage
Animal myAnimal = new Dog();
myAnimal.MakeSound(); // Output: Dog barks.
In this example, the MakeSound()
method is overridden in the Dog
class using the override
keyword.
Inheritance vs. Interfaces
Feature | Inheritance | Interfaces |
---|---|---|
Definition | Allows a class to derive properties and methods from another class. | Defines a contract that implementing classes must follow. |
Multiple Support | Single inheritance (one base class only). | Supports multiple implementations. |
Default Implementation | Base class can provide default method implementations. | Until C# 8.0, interfaces could not have method implementations. |
Use Case | For reusing code across related classes. | For enforcing rules across multiple unrelated classes. |
Benefits of Using Inheritance
- Reduces redundancy by reusing base class members.
- Improves maintainability and scalability of code.
- Allows method overriding for customized behavior.
- Supports polymorphism, enabling flexible code design.